Search in sources :

Example 11 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class StatementRegressionTest method testBug11540.

@Test
public void testBug11540() throws Exception {
    Locale originalLocale = Locale.getDefault();
    Connection thaiConn = null;
    Statement thaiStmt = null;
    PreparedStatement thaiPrepStmt = null;
    try {
        createTable("testBug11540", "(field1 DATE, field2 DATETIME)");
        this.stmt.executeUpdate("INSERT INTO testBug11540 VALUES (NOW(), NOW())");
        Locale.setDefault(new Locale("th", "TH"));
        Properties props = new Properties();
        props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        props.setProperty(PropertyKey.jdbcCompliantTruncation.getKeyName(), "false");
        props.setProperty(PropertyKey.connectionTimeZone.getKeyName(), "LOCAL");
        thaiConn = getConnectionWithProps(props);
        thaiStmt = thaiConn.createStatement();
        this.rs = thaiStmt.executeQuery("SELECT field1, field2 FROM testBug11540");
        this.rs.next();
        Date origDate = this.rs.getDate(1);
        Timestamp origTimestamp = this.rs.getTimestamp(2);
        this.rs.close();
        thaiStmt.executeUpdate("TRUNCATE TABLE testBug11540");
        thaiPrepStmt = ((com.mysql.cj.jdbc.JdbcConnection) thaiConn).clientPrepareStatement("INSERT INTO testBug11540 VALUES (?,?)");
        thaiPrepStmt.setDate(1, origDate);
        thaiPrepStmt.setTimestamp(2, origTimestamp);
        thaiPrepStmt.executeUpdate();
        this.rs = thaiStmt.executeQuery("SELECT field1, field2 FROM testBug11540");
        this.rs.next();
        Date testDate = this.rs.getDate(1);
        Timestamp testTimestamp = this.rs.getTimestamp(2);
        this.rs.close();
        props = new Properties();
        props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        props.setProperty(PropertyKey.connectionTimeZone.getKeyName(), "LOCAL");
        Connection testConn = getConnectionWithProps(props);
        TimeZone serverTz = ((MysqlConnection) testConn).getSession().getServerSession().getSessionTimeZone();
        Timestamp expTs = Timestamp.from(origTimestamp.toInstant().atZone(ZoneId.systemDefault()).withZoneSameInstant(serverTz.toZoneId()).withZoneSameLocal(ZoneId.systemDefault()).toInstant());
        assertEquals(origDate, testDate);
        assertEquals(expTs, testTimestamp);
    } finally {
        Locale.setDefault(originalLocale);
    }
}
Also used : Locale(java.util.Locale) TimeZone(java.util.TimeZone) JdbcStatement(com.mysql.cj.jdbc.JdbcStatement) JdbcPreparedStatement(com.mysql.cj.jdbc.JdbcPreparedStatement) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) JdbcPreparedStatement(com.mysql.cj.jdbc.JdbcPreparedStatement) PreparedStatement(java.sql.PreparedStatement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) MysqlConnection(com.mysql.cj.MysqlConnection) Properties(java.util.Properties) Timestamp(java.sql.Timestamp) LocalDate(java.time.LocalDate) Date(java.sql.Date) StatementsTest(testsuite.simple.StatementsTest) Test(org.junit.jupiter.api.Test)

Example 12 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class StatementRegressionTest method testLoadData.

/*
     * public void testBug9595() throws Exception { double[] vals = new double[]
     * {52.21, 52.22, 52.23, 52.24};
     * 
     * createTable("testBug9595", "(field1 DECIMAL(10,2), sortField INT)");
     * 
     * this.pstmt = this.conn.prepareStatement("INSERT INTO testBug9595 VALUES
     * (?, ?)"); // Try setting as doubles for (int i = 0; i < vals.length; i++)
     * { this.pstmt.setDouble(1, vals[i]); this.pstmt.setInt(2, i);
     * this.pstmt.executeUpdate(); }
     * 
     * this.pstmt = this.conn.prepareStatement("SELECT field1 FROM testBug9595
     * ORDER BY sortField"); this.rs = this.pstmt.executeQuery();
     * 
     * int i = 0;
     * 
     * while (this.rs.next()) { double valToTest = vals[i++];
     * 
     * assertEquals(this.rs.getDouble(1), valToTest, 0.001);
     * assertEquals(this.rs.getBigDecimal(1).doubleValue(), valToTest, 0.001); }
     * 
     * this.pstmt = this.conn.prepareStatement("INSERT INTO testBug9595 VALUES
     * (?, ?)");
     * 
     * this.stmt.executeUpdate("TRUNCATE TABLE testBug9595"); // Now, as
     * BigDecimals for (i = 0; i < vals.length; i++) { BigDecimal foo = new
     * BigDecimal(vals[i]);
     * 
     * this.pstmt.setObject(1, foo, Types.DECIMAL, 2); this.pstmt.setInt(2, i);
     * this.pstmt.executeUpdate(); }
     * 
     * this.pstmt = this.conn.prepareStatement("SELECT field1 FROM testBug9595
     * ORDER BY sortField"); this.rs = this.pstmt.executeQuery();
     * 
     * i = 0;
     * 
     * while (this.rs.next()) { double valToTest = vals[i++];
     * System.out.println(this.rs.getString(1));
     * assertEquals(this.rs.getDouble(1), valToTest, 0.001);
     * assertEquals(this.rs.getBigDecimal(1).doubleValue(), valToTest, 0.001); }
     * }
     */
/**
 * Tests that 'LOAD DATA LOCAL INFILE' works
 *
 * @throws Exception
 */
@Test
public void testLoadData() throws Exception {
    assumeTrue(supportsLoadLocalInfile(this.stmt), "This test requires the server started with --local-infile=ON");
    createTable("loadDataRegress", "(field1 int, field2 int)");
    // int maxAllowedPacket = 1048576;
    File tempFile = File.createTempFile("mysql", ".txt");
    // tempFile.deleteOnExit();
    System.out.println(tempFile);
    Writer out = new FileWriter(tempFile);
    int localCount = 0;
    // maxAllowedPacket * 4;
    int rowCount = 128;
    for (int i = 0; i < rowCount; i++) {
        out.write((localCount++) + "\t" + (localCount++) + "\n");
    }
    out.close();
    StringBuilder fileNameBuf = null;
    if (File.separatorChar == '\\') {
        fileNameBuf = new StringBuilder();
        String fileName = tempFile.getAbsolutePath();
        int fileNameLength = fileName.length();
        for (int i = 0; i < fileNameLength; i++) {
            char c = fileName.charAt(i);
            if (c == '\\') {
                fileNameBuf.append("/");
            } else {
                fileNameBuf.append(c);
            }
        }
    } else {
        fileNameBuf = new StringBuilder(tempFile.getAbsolutePath());
    }
    final String fileName = fileNameBuf.toString();
    assertThrows(SQLSyntaxErrorException.class, versionMeetsMinimum(8, 0, 19) ? "Loading local data is disabled;.*" : "The used command is not allowed with this MySQL version", () -> {
        this.stmt.executeUpdate("LOAD DATA LOCAL INFILE '" + fileName + "' INTO TABLE loadDataRegress CHARACTER SET " + CharsetMappingWrapper.getStaticMysqlCharsetForJavaEncoding(((MysqlConnection) this.conn).getPropertySet().getStringProperty(PropertyKey.characterEncoding).getValue(), this.serverVersion));
        return null;
    });
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    props.setProperty(PropertyKey.allowLoadLocalInfile.getKeyName(), "true");
    Connection testConn = getConnectionWithProps(props);
    int updateCount = testConn.createStatement().executeUpdate("LOAD DATA LOCAL INFILE '" + fileNameBuf.toString() + "' INTO TABLE loadDataRegress CHARACTER SET " + CharsetMappingWrapper.getStaticMysqlCharsetForJavaEncoding(((MysqlConnection) this.conn).getPropertySet().getStringProperty(PropertyKey.characterEncoding).getValue(), this.serverVersion));
    assertTrue(updateCount == rowCount);
}
Also used : FileWriter(java.io.FileWriter) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) Properties(java.util.Properties) File(java.io.File) Writer(java.io.Writer) FileWriter(java.io.FileWriter) StatementsTest(testsuite.simple.StatementsTest) Test(org.junit.jupiter.api.Test)

Example 13 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ConnectionRegressionTest method assertCurrentUser.

private void assertCurrentUser(String url, Properties props, String expectedUser, boolean sslRequired) throws SQLException {
    Connection connection = url == null ? getConnectionWithProps(props) : getConnectionWithProps(url, props);
    if (sslRequired) {
        assertTrue(((MysqlConnection) connection).getSession().isSSLEstablished(), "SSL connection isn't established!");
    }
    Statement st = connection.createStatement();
    ResultSet rset = st.executeQuery("SELECT USER(), CURRENT_USER()");
    rset.next();
    assertEquals(expectedUser, rset.getString(1).split("@")[0]);
    assertEquals(expectedUser, rset.getString(2).split("@")[0]);
    connection.close();
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) ResultSet(java.sql.ResultSet) MysqlConnection(com.mysql.cj.MysqlConnection)

Example 14 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ConnectionRegressionTest method testBug88242.

/**
 * Tests fix for Bug#88242 - autoReconnect and socketTimeout JDBC option makes wrong order of client packet.
 *
 * The wrong behavior may not be observed in all systems or configurations. It seems to be easier to reproduce when SSL is enabled. Without it, the data
 * packets flow faster and desynchronization occurs rarely, which is the root cause for this problem.
 *
 * @throws Exception
 */
@Test
public void testBug88242() throws Exception {
    assumeTrue((((MysqlConnection) this.conn).getSession().getServerSession().getCapabilities().getCapabilityFlags() & NativeServerSession.CLIENT_SSL) != 0, "This test requires server with SSL support.");
    assumeTrue(supportsTLSv1_2(((MysqlConnection) this.conn).getSession().getServerSession().getServerVersion()), "This test requires server with TLSv1.2+ support.");
    assumeTrue(supportsTestCertificates(this.stmt), "This test requires the server configured with SSL certificates from ConnectorJ/src/test/config/ssl-test-certs");
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.name());
    props.setProperty(PropertyKey.autoReconnect.getKeyName(), "true");
    props.setProperty(PropertyKey.socketTimeout.getKeyName(), "1500");
    Connection testConn = getConnectionWithProps(props);
    PreparedStatement ps = testConn.prepareStatement("SELECT ?, SLEEP(?)");
    int key = 0;
    for (int i = 0; i < 5; i++) {
        // Execute a query that runs faster than the socket timeout limit.
        ps.setInt(1, ++key);
        ps.setInt(2, 0);
        try {
            ResultSet rset = ps.executeQuery();
            assertTrue(rset.next());
            assertEquals(key, rset.getInt(1));
        } catch (SQLException e) {
            e.printStackTrace();
            fail("Exception [" + e.getClass().getName() + ": " + e.getMessage() + "] caught when no exception was expected.");
        }
        // Execute a query that runs slower than the socket timeout limit.
        ps.setInt(1, ++key);
        ps.setInt(2, 2);
        final PreparedStatement localPstmt = ps;
        assertThrows("Communications link failure.*", SQLException.class, new Callable<Void>() {

            public Void call() throws Exception {
                localPstmt.executeQuery();
                return null;
            }
        });
    }
    testConn.close();
}
Also used : SQLException(java.sql.SQLException) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) ResultSet(java.sql.ResultSet) MysqlConnection(com.mysql.cj.MysqlConnection) PreparedStatement(java.sql.PreparedStatement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) Properties(java.util.Properties) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLTransientException(java.sql.SQLTransientException) InvocationTargetException(java.lang.reflect.InvocationTargetException) XAException(javax.transaction.xa.XAException) SocketException(java.net.SocketException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) SQLNonTransientConnectionException(java.sql.SQLNonTransientConnectionException) CommunicationsException(com.mysql.cj.jdbc.exceptions.CommunicationsException) CertificateException(java.security.cert.CertificateException) ClosedOnExpiredPasswordException(com.mysql.cj.exceptions.ClosedOnExpiredPasswordException) PropertyNotModifiableException(com.mysql.cj.exceptions.PropertyNotModifiableException) Test(org.junit.jupiter.api.Test)

Example 15 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ConnectionRegressionTest method testAuthCleartextPlugin.

@Test
public void testAuthCleartextPlugin() throws Exception {
    assumeTrue((((MysqlConnection) this.conn).getSession().getServerSession().getCapabilities().getCapabilityFlags() & NativeServerSession.CLIENT_SSL) != 0, "This test requires server with SSL support.");
    assumeTrue(supportsTLSv1_2(((MysqlConnection) this.conn).getSession().getServerSession().getServerVersion()), "This test requires server with TLSv1.2+ support.");
    assumeTrue(supportsTestCertificates(this.stmt), "This test requires the server configured with SSL certificates from ConnectorJ/src/test/config/ssl-test-certs");
    boolean installPluginInRuntime = false;
    try {
        // Install plugin if required.
        this.rs = this.stmt.executeQuery("SELECT (PLUGIN_LIBRARY LIKE 'auth_test_plugin%') as `TRUE` FROM INFORMATION_SCHEMA.PLUGINS " + "WHERE PLUGIN_NAME='cleartext_plugin_server'");
        if (this.rs.next()) {
            installPluginInRuntime = !this.rs.getBoolean(1);
        } else {
            installPluginInRuntime = true;
        }
        if (installPluginInRuntime) {
            try {
                String ext = isServerRunningOnWindows() ? ".dll" : ".so";
                this.stmt.executeUpdate("INSTALL PLUGIN cleartext_plugin_server SONAME 'auth_test_plugin" + ext + "'");
            } catch (SQLException e) {
                if (e.getErrorCode() == MysqlErrorNumbers.ER_CANT_OPEN_LIBRARY) {
                    // To disable plugin deinstallation attempt in the finally block.
                    installPluginInRuntime = false;
                    assumeTrue(false, "This test requires a server installed with the test package.");
                } else {
                    throw e;
                }
            }
        }
        String dbname = getPropertiesFromTestsuiteUrl().getProperty(PropertyKey.DBNAME.getKeyName());
        assertFalse(StringUtils.isNullOrEmpty(dbname), "No database selected");
        createUser("'wl5735user'@'%'", "identified WITH cleartext_plugin_server AS ''");
        this.stmt.executeUpdate("DELETE FROM mysql.db WHERE user='wl5735user'");
        this.stmt.executeUpdate("INSERT INTO mysql.db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, " + "Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Create_tmp_table_priv, Lock_tables_priv, Create_view_priv, " + "Show_view_priv, Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv) VALUES ('%', '" + dbname + "', 'wl5735user', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'N', 'N')");
        this.stmt.executeUpdate("FLUSH PRIVILEGES");
        Properties props = new Properties();
        props.setProperty(PropertyKey.USER.getKeyName(), "wl5735user");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "");
        props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
        assertThrows(SQLException.class, "SSL connection required for plugin \"mysql_clear_password\"\\. Check if 'sslMode' is enabled\\.", () -> getConnectionWithProps(props));
        String trustStorePath = "src/test/config/ssl-test-certs/ca-truststore";
        System.setProperty("javax.net.ssl.trustStore", trustStorePath);
        System.setProperty("javax.net.ssl.trustStorePassword", "password");
        props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.name());
        try (Connection testConn = getConnectionWithProps(props)) {
            assertTrue(((MysqlConnection) testConn).getSession().isSSLEstablished(), "SSL connection isn't actually established!");
            Statement testSt = testConn.createStatement();
            ResultSet testRs = testSt.executeQuery("SELECT USER(), CURRENT_USER()");
            assertTrue(testRs.next());
            assertEquals("wl5735user", testRs.getString(1).split("@")[0]);
            assertEquals("wl5735user", testRs.getString(2).split("@")[0]);
        }
    } finally {
        if (installPluginInRuntime) {
            this.stmt.executeUpdate("UNINSTALL PLUGIN cleartext_plugin_server");
        }
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) ResultSet(java.sql.ResultSet) MysqlConnection(com.mysql.cj.MysqlConnection) Properties(java.util.Properties) Test(org.junit.jupiter.api.Test)

Aggregations

MysqlConnection (com.mysql.cj.MysqlConnection)70 Test (org.junit.jupiter.api.Test)65 Properties (java.util.Properties)57 Connection (java.sql.Connection)55 JdbcConnection (com.mysql.cj.jdbc.JdbcConnection)42 TimeZone (java.util.TimeZone)26 XAConnection (javax.sql.XAConnection)24 ReplicationConnection (com.mysql.cj.jdbc.ha.ReplicationConnection)23 PooledConnection (javax.sql.PooledConnection)22 MysqlPooledConnection (com.mysql.cj.jdbc.MysqlPooledConnection)21 MysqlXAConnection (com.mysql.cj.jdbc.MysqlXAConnection)21 SuspendableXAConnection (com.mysql.cj.jdbc.SuspendableXAConnection)21 ZonedDateTime (java.time.ZonedDateTime)21 SQLException (java.sql.SQLException)18 PreparedStatement (java.sql.PreparedStatement)16 Statement (java.sql.Statement)16 CommunicationsException (com.mysql.cj.jdbc.exceptions.CommunicationsException)14 IOException (java.io.IOException)14 ExecutionException (java.util.concurrent.ExecutionException)14 TimeoutException (java.util.concurrent.TimeoutException)14