Search in sources :

Example 16 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class StatementRegressionTest method testBug87429.

/**
 * Tests fix for Bug#87429 - repeated close of ServerPreparedStatement causes memory leak.
 *
 * Original de-cache on double close() behavior modified by:
 * WL#11101 - Remove de-cache and close of SSPSs on double call to close().
 *
 * @throws Exception
 */
@Test
public void testBug87429() throws Exception {
    Field stmtsCacheField = ConnectionImpl.class.getDeclaredField("serverSideStatementCache");
    stmtsCacheField.setAccessible(true);
    ToIntFunction<Connection> getStmtsCacheSize = (c) -> {
        try {
            LRUCache<?, ?> stmtsCacheObj = (LRUCache<?, ?>) stmtsCacheField.get(c);
            return stmtsCacheObj == null ? -1 : stmtsCacheObj.size();
        } catch (IllegalArgumentException | IllegalAccessException e) {
            fail("Fail getting the statemets cache size.");
            return -1;
        }
    };
    final String sql1 = "SELECT 1, ?";
    final String sql2 = "SELECT 2, ?";
    boolean useSPS = false;
    boolean cachePS = false;
    do {
        Properties props = new Properties();
        props.setProperty(PropertyKey.useSSL.getKeyName(), "false");
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        props.setProperty(PropertyKey.useServerPrepStmts.getKeyName(), Boolean.toString(useSPS));
        props.setProperty(PropertyKey.cachePrepStmts.getKeyName(), Boolean.toString(cachePS));
        props.setProperty(PropertyKey.prepStmtCacheSize.getKeyName(), "5");
        boolean cachedSPS = useSPS && cachePS;
        JdbcConnection testConn = (JdbcConnection) getConnectionWithProps(props);
        // Single PreparedStatement, closed multiple times.
        for (int i = 0; i < 100; i++) {
            this.pstmt = testConn.prepareStatement(sql1);
            assertTrue(this.pstmt.isPoolable());
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // Close & cache.
            this.pstmt.close();
            assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // No-op.
            this.pstmt.close();
            assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // No-op.
            this.pstmt.close();
            assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            try {
                // De-caches the statement or no-op if not cached.
                this.pstmt.setPoolable(false);
            } catch (SQLException e) {
                assertFalse(cachedSPS, "Exception [" + e.getMessage() + "] not expected.");
            }
            // No-op.
            this.pstmt.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
        }
        testConn.close();
        assertEquals(0, testConn.getActiveStatementCount());
        assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
        testConn = (JdbcConnection) getConnectionWithProps(props);
        // Multiple PreparedStatements interchanged, two queries, closed multiple times.
        for (int i = 0; i < 100; i++) {
            for (int j = 1; j <= 4; j++) {
                PreparedStatement pstmt1 = testConn.prepareStatement(j == 1 ? sql2 : sql1);
                PreparedStatement pstmt2 = testConn.prepareStatement(j == 2 ? sql2 : sql1);
                PreparedStatement pstmt3 = testConn.prepareStatement(j == 3 ? sql2 : sql1);
                PreparedStatement pstmt4 = testConn.prepareStatement(j == 4 ? sql2 : sql1);
                assertEquals(4, testConn.getActiveStatementCount());
                // Close and cache statements successively.
                pstmt4.close();
                // No-op.
                pstmt4.close();
                assertEquals(cachedSPS ? 4 : 3, testConn.getActiveStatementCount());
                pstmt3.close();
                // No-op.
                pstmt3.close();
                assertEquals(cachedSPS ? (j >= 3 ? 4 : 3) : 2, testConn.getActiveStatementCount());
                pstmt2.close();
                // No-op.
                pstmt2.close();
                assertEquals(cachedSPS ? (j >= 2 ? 3 : 2) : 1, testConn.getActiveStatementCount());
                pstmt1.close();
                // No-op.
                pstmt1.close();
                assertEquals(cachedSPS ? 2 : 0, testConn.getActiveStatementCount());
                // No-ops.
                pstmt4.close();
                pstmt4.close();
                pstmt3.close();
                pstmt3.close();
                pstmt2.close();
                pstmt2.close();
                pstmt1.close();
                pstmt1.close();
                assertEquals(cachedSPS ? 2 : 0, testConn.getActiveStatementCount());
                // De-cache statements successively.
                try {
                    // De-caches the statement or no-op if not cached.
                    pstmt4.setPoolable(false);
                } catch (SQLException e) {
                    assertFalse(cachedSPS && j == 4, "Exception [" + e.getMessage() + "] not expected.");
                }
                // No-op.
                pstmt4.close();
                assertEquals(cachedSPS ? (j < 4 ? 2 : 1) : 0, testConn.getActiveStatementCount());
                try {
                    // De-caches the statement or no-op if not cached.
                    pstmt3.setPoolable(false);
                } catch (SQLException e) {
                    assertFalse(cachedSPS && j == 3, "Exception [" + e.getMessage() + "] not expected.");
                }
                // No-op.
                pstmt3.close();
                assertEquals(cachedSPS ? (j < 3 ? 2 : 1) : 0, testConn.getActiveStatementCount());
                try {
                    // De-caches the statement or no-op if not cached.
                    pstmt2.setPoolable(false);
                } catch (SQLException e) {
                    assertFalse(cachedSPS && j == 2, "Exception [" + e.getMessage() + "] not expected.");
                }
                // No-op.
                pstmt2.close();
                assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
                try {
                    // De-caches the statement or no-op if not cached.
                    pstmt1.setPoolable(false);
                } catch (SQLException e) {
                    assertFalse(cachedSPS, "Exception [" + e.getMessage() + "] not expected.");
                }
                // No-op.
                pstmt1.close();
                assertEquals(0, testConn.getActiveStatementCount());
            }
        }
        testConn.close();
        assertEquals(0, testConn.getActiveStatementCount());
    } while ((useSPS = !useSPS) || (cachePS = !cachePS));
}
Also used : Arrays(java.util.Arrays) BaseTestCase(testsuite.BaseTestCase) CharArrayReader(java.io.CharArrayReader) SerialBlob(javax.sql.rowset.serial.SerialBlob) Disabled(org.junit.jupiter.api.Disabled) NativeServerSession(com.mysql.cj.protocol.a.NativeServerSession) JdbcStatement(com.mysql.cj.jdbc.JdbcStatement) BigDecimal(java.math.BigDecimal) Future(java.util.concurrent.Future) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlXADataSource(com.mysql.cj.jdbc.MysqlXADataSource) Assumptions.assumeFalse(org.junit.jupiter.api.Assumptions.assumeFalse) ResultSet(java.sql.ResultSet) Map(java.util.Map) BigInteger(java.math.BigInteger) CharsetMappingWrapper(com.mysql.cj.CharsetMappingWrapper) NClob(java.sql.NClob) WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) CJCommunicationsException(com.mysql.cj.exceptions.CJCommunicationsException) DataTruncation(java.sql.DataTruncation) GregorianCalendar(java.util.GregorianCalendar) ClientPreparedQuery(com.mysql.cj.ClientPreparedQuery) ParameterBindings(com.mysql.cj.jdbc.ParameterBindings) JdbcPreparedStatement(com.mysql.cj.jdbc.JdbcPreparedStatement) Reader(java.io.Reader) Assertions.assertNotSame(org.junit.jupiter.api.Assertions.assertNotSame) PreparedStatement(java.sql.PreparedStatement) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) RowId(java.sql.RowId) Ref(java.sql.Ref) ResultSetScannerInterceptor(com.mysql.cj.jdbc.interceptors.ResultSetScannerInterceptor) Assertions.fail(org.junit.jupiter.api.Assertions.fail) MysqlErrorNumbers(com.mysql.cj.exceptions.MysqlErrorNumbers) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UnreliableSocketFactory(testsuite.UnreliableSocketFactory) BatchUpdateException(java.sql.BatchUpdateException) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) LocalDateTime(java.time.LocalDateTime) SimpleDateFormat(java.text.SimpleDateFormat) Callable(java.util.concurrent.Callable) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) Calendar(java.util.Calendar) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Clob(java.sql.Clob) Properties(java.util.Properties) ColumnDefinition(com.mysql.cj.protocol.ColumnDefinition) Log(com.mysql.cj.log.Log) ToIntFunction(java.util.function.ToIntFunction) ConnectionImpl(com.mysql.cj.jdbc.ConnectionImpl) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Field(java.lang.reflect.Field) File(java.io.File) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) ExecutionException(java.util.concurrent.ExecutionException) StringReader(java.io.StringReader) Statement(java.sql.Statement) Connection(java.sql.Connection) Time(java.sql.Time) ExceptionFactory(com.mysql.cj.exceptions.ExceptionFactory) URL(java.net.URL) XAConnection(javax.sql.XAConnection) CachedResultSetMetaData(com.mysql.cj.jdbc.result.CachedResultSetMetaData) SQLXML(java.sql.SQLXML) TimeoutException(java.util.concurrent.TimeoutException) Array(java.sql.Array) CompletionService(java.util.concurrent.CompletionService) ResultSetInternalMethods(com.mysql.cj.jdbc.result.ResultSetInternalMethods) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) LocalTime(java.time.LocalTime) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) StatementsTest(testsuite.simple.StatementsTest) SQLWarning(java.sql.SQLWarning) Resultset(com.mysql.cj.protocol.Resultset) ServerSession(com.mysql.cj.protocol.ServerSession) TimeZone(java.util.TimeZone) Timestamp(java.sql.Timestamp) Query(com.mysql.cj.Query) MysqlConnectionPoolDataSource(com.mysql.cj.jdbc.MysqlConnectionPoolDataSource) Session(com.mysql.cj.Session) Test(org.junit.jupiter.api.Test) List(java.util.List) LocalDate(java.time.LocalDate) Writer(java.io.Writer) CallableStatement(java.sql.CallableStatement) MySQLTimeoutException(com.mysql.cj.jdbc.exceptions.MySQLTimeoutException) ResultSetMetaData(java.sql.ResultSetMetaData) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) Types(java.sql.Types) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) ServerPreparedQuery(com.mysql.cj.ServerPreparedQuery) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) CommunicationsException(com.mysql.cj.jdbc.exceptions.CommunicationsException) ExecutorService(java.util.concurrent.ExecutorService) PrintStream(java.io.PrintStream) FileWriter(java.io.FileWriter) LRUCache(com.mysql.cj.util.LRUCache) TimeUtil(com.mysql.cj.util.TimeUtil) Date(java.sql.Date) DatabaseTerm(com.mysql.cj.conf.PropertyDefinitions.DatabaseTerm) TimeUnit(java.util.concurrent.TimeUnit) StatementImpl(com.mysql.cj.jdbc.StatementImpl) BaseQueryInterceptor(testsuite.BaseQueryInterceptor) MysqlConnection(com.mysql.cj.MysqlConnection) Blob(java.sql.Blob) ResultsetRows(com.mysql.cj.protocol.ResultsetRows) PropertyKey(com.mysql.cj.conf.PropertyKey) QueryInterceptor(com.mysql.cj.interceptors.QueryInterceptor) InputStream(java.io.InputStream) Field(java.lang.reflect.Field) LRUCache(com.mysql.cj.util.LRUCache) SQLException(java.sql.SQLException) 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) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) JdbcPreparedStatement(com.mysql.cj.jdbc.JdbcPreparedStatement) PreparedStatement(java.sql.PreparedStatement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) Properties(java.util.Properties) StatementsTest(testsuite.simple.StatementsTest) Test(org.junit.jupiter.api.Test)

Example 17 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testBug21947042.

/**
 * Tests fix for BUG#21947042, PREFER TLS WHERE SUPPORTED BY MYSQL SERVER.
 *
 * Requires test certificates from testsuite/ssl-test-certs to be installed on the server being tested.
 *
 * @throws Exception
 */
@Test
public void testBug21947042() throws Exception {
    assumeTrue(supportsTestCertificates(this.stmt), "This test requires the server configured with SSL certificates from ConnectorJ/src/test/config/ssl-test-certs");
    System.setProperty("javax.net.ssl.trustStore", "");
    System.setProperty("javax.net.ssl.trustStorePassword", "");
    Connection sslConn = null;
    Properties props = new Properties();
    // 1. No explicit useSSL
    sslConn = getConnectionWithProps(props);
    assertFalse(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.PREFERRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    // 2. Explicit useSSL=false
    props.setProperty(PropertyKey.useSSL.getKeyName(), "false");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.DISABLED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertFalse(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    props.setProperty(PropertyKey.useSSL.getKeyName(), "no");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.DISABLED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertFalse(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    // 2.1. Explicit useSSL=false, requireSSL=true
    props.setProperty(PropertyKey.useSSL.getKeyName(), "false");
    props.setProperty(PropertyKey.requireSSL.getKeyName(), "true");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.DISABLED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertFalse(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    props.setProperty(PropertyKey.useSSL.getKeyName(), "no");
    props.setProperty(PropertyKey.requireSSL.getKeyName(), "yes");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.DISABLED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertFalse(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    props.remove(PropertyKey.requireSSL.getKeyName());
    // 3. Explicit useSSL=true
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    sslConn = getConnectionWithProps(props);
    assertFalse(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.PREFERRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    props.setProperty(PropertyKey.useSSL.getKeyName(), "yes");
    sslConn = getConnectionWithProps(props);
    assertFalse(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.PREFERRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    // 3.1. Explicit useSSL=true, requireSSL=true
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.requireSSL.getKeyName(), "true");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.REQUIRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    props.setProperty(PropertyKey.useSSL.getKeyName(), "yes");
    props.setProperty(PropertyKey.requireSSL.getKeyName(), "yes");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.REQUIRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    // 4. Explicit useSSL=true, verifyServerCertificate=true, no trust store
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "true");
    assertThrows(SQLException.class, new Callable<Void>() {

        public Void call() throws Exception {
            getConnectionWithProps(props);
            return null;
        }
    });
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "yes");
    assertThrows(SQLException.class, new Callable<Void>() {

        public Void call() throws Exception {
            getConnectionWithProps(props);
            return null;
        }
    });
    // 5. Explicit useSSL=true, verifyServerCertificate=true
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "true");
    props.setProperty(PropertyKey.trustCertificateKeyStoreUrl.getKeyName(), "file:src/test/config/ssl-test-certs/ca-truststore");
    props.setProperty(PropertyKey.trustCertificateKeyStoreType.getKeyName(), "JKS");
    props.setProperty(PropertyKey.trustCertificateKeyStorePassword.getKeyName(), "password");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.VERIFY_CA, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
    props.setProperty(PropertyKey.useSSL.getKeyName(), "yes");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "yes");
    props.setProperty(PropertyKey.trustCertificateKeyStoreUrl.getKeyName(), "file:src/test/config/ssl-test-certs/ca-truststore");
    props.setProperty(PropertyKey.trustCertificateKeyStoreType.getKeyName(), "JKS");
    props.setProperty(PropertyKey.trustCertificateKeyStorePassword.getKeyName(), "password");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.VERIFY_CA, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    testBug21947042_PrintCipher(sslConn);
    testBug21947042_PrintVersion(sslConn);
    sslConn.close();
}
Also used : 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) MysqlConnection(com.mysql.cj.MysqlConnection) 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 18 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testBug75592.

/**
 * Tests fix for BUG#75592 - "SHOW VARIABLES WHERE" is expensive.
 *
 * @throws Exception
 */
@Test
public void testBug75592() throws Exception {
    if (versionMeetsMinimum(5, 0, 3)) {
        Properties props = new Properties();
        props.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        props.setProperty(PropertyKey.queryInterceptors.getKeyName(), Bug75592QueryInterceptor.class.getName());
        JdbcConnection con = (JdbcConnection) getConnectionWithProps(props);
        // reference values
        Map<String, String> serverVariables = new HashMap<>();
        this.rs = con.createStatement().executeQuery("SHOW VARIABLES");
        while (this.rs.next()) {
            String val = this.rs.getString(2);
            serverVariables.put(this.rs.getString(1), "utf8mb3".equals(val) ? "utf8" : val);
        }
        // fix the renaming of "tx_isolation" to "transaction_isolation" that is made in NativeSession.loadServerVariables().
        if (!serverVariables.containsKey("transaction_isolation") && serverVariables.containsKey("tx_isolation")) {
            serverVariables.put("transaction_isolation", serverVariables.remove("tx_isolation"));
        }
        Session session = con.getSession();
        // check values from "select @@var..."
        assertEquals(serverVariables.get("auto_increment_increment"), session.getServerSession().getServerVariable("auto_increment_increment"));
        assertEquals(serverVariables.get(CharsetSettings.CHARACTER_SET_CLIENT), session.getServerSession().getServerVariable(CharsetSettings.CHARACTER_SET_CLIENT));
        assertEquals(serverVariables.get(CharsetSettings.CHARACTER_SET_CONNECTION), session.getServerSession().getServerVariable(CharsetSettings.CHARACTER_SET_CONNECTION));
        // we override character_set_results sometimes when configuring client charsets, thus need to check against actual value
        if (session.getServerSession().getServerVariable(CharsetSettings.CHARACTER_SET_RESULTS) == null) {
            assertEquals("", serverVariables.get(CharsetSettings.CHARACTER_SET_RESULTS));
        } else {
            assertEquals(serverVariables.get(CharsetSettings.CHARACTER_SET_RESULTS), session.getServerSession().getServerVariable(CharsetSettings.CHARACTER_SET_RESULTS));
        }
        assertEquals(serverVariables.get("character_set_server"), session.getServerSession().getServerVariable("character_set_server"));
        assertEquals(serverVariables.get("init_connect"), session.getServerSession().getServerVariable("init_connect"));
        assertEquals(serverVariables.get("interactive_timeout"), session.getServerSession().getServerVariable("interactive_timeout"));
        assertEquals(serverVariables.get("license"), session.getServerSession().getServerVariable("license"));
        assertEquals(serverVariables.get("lower_case_table_names"), session.getServerSession().getServerVariable("lower_case_table_names"));
        assertEquals(serverVariables.get("max_allowed_packet"), session.getServerSession().getServerVariable("max_allowed_packet"));
        assertEquals(serverVariables.get("net_write_timeout"), session.getServerSession().getServerVariable("net_write_timeout"));
        if (!con.getServerVersion().meetsMinimum(new ServerVersion(8, 0, 3))) {
            assertEquals(serverVariables.get("query_cache_size"), session.getServerSession().getServerVariable("query_cache_size"));
            assertEquals(serverVariables.get("query_cache_type"), session.getServerSession().getServerVariable("query_cache_type"));
        }
        // not necessarily contains STRICT_TRANS_TABLES
        for (String sm : serverVariables.get("sql_mode").split(",")) {
            if (!sm.equals("STRICT_TRANS_TABLES")) {
                assertTrue(session.getServerSession().getServerVariable("sql_mode").contains(sm));
            }
        }
        assertEquals(serverVariables.get("system_time_zone"), session.getServerSession().getServerVariable("system_time_zone"));
        assertEquals(serverVariables.get("time_zone"), session.getServerSession().getServerVariable("time_zone"));
        assertEquals(serverVariables.get("transaction_isolation"), session.getServerSession().getServerVariable("transaction_isolation"));
        assertEquals(serverVariables.get("wait_timeout"), session.getServerSession().getServerVariable("wait_timeout"));
        if (!versionMeetsMinimum(5, 5, 0)) {
            assertEquals(serverVariables.get("language"), session.getServerSession().getServerVariable("language"));
        }
    }
}
Also used : ServerVersion(com.mysql.cj.ServerVersion) HashMap(java.util.HashMap) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) Properties(java.util.Properties) NativeServerSession(com.mysql.cj.protocol.a.NativeServerSession) NativeSession(com.mysql.cj.NativeSession) ServerSession(com.mysql.cj.protocol.ServerSession) Session(com.mysql.cj.Session) Test(org.junit.jupiter.api.Test)

Example 19 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testBug29329326.

/**
 * Tests fix for Bug#29329326, PLEASE AVOID SHOW PROCESSLIST IF POSSIBLE.
 *
 * @throws Exception
 */
@Test
public void testBug29329326() throws Exception {
    Properties p = new Properties();
    p.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
    p.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    p.setProperty(PropertyKey.queryInterceptors.getKeyName(), Bug29329326QueryInterceptor.class.getName());
    JdbcConnection c = (JdbcConnection) getConnectionWithProps(p);
    Bug29329326QueryInterceptor qi = (Bug29329326QueryInterceptor) c.getQueryInterceptorsInstances().get(0);
    assertTrue(qi.cnt == 0, "SHOW PROCESSLIST was issued during connection establishing");
    ((com.mysql.cj.jdbc.ConnectionImpl) c).isServerLocal();
    String ps = ((MysqlConnection) c).getSession().getServerSession().getServerVariable("performance_schema");
    if (// performance_schema.threads in MySQL 5.5 does not contain PROCESSLIST_HOST column
    versionMeetsMinimum(5, 6, 0) && ps != null && ("1".contentEquals(ps) || "ON".contentEquals(ps))) {
        assertTrue(qi.cnt == 0, "SHOW PROCESSLIST was issued by isServerLocal()");
    } else {
        assertTrue(qi.cnt > 0, "SHOW PROCESSLIST wasn't issued by isServerLocal()");
    }
}
Also used : ConnectionImpl(com.mysql.cj.jdbc.ConnectionImpl) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) Properties(java.util.Properties) Test(org.junit.jupiter.api.Test)

Example 20 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testBug20825727ChangePassword.

private void testBug20825727ChangePassword(String testDbUrl, String user, String password, String pluginName, int pwdHashingMethod) throws SQLException {
    JdbcConnection testConn = null;
    try {
        Properties props = new Properties();
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        props.setProperty(PropertyKey.characterEncoding.getKeyName(), "UTF-8");
        testConn = (JdbcConnection) getConnectionWithProps(testDbUrl, props);
        Statement testStmt = testConn.createStatement();
        if (testConn.getSession().versionMeetsMinimum(5, 7, 6)) {
            testStmt.execute("ALTER USER '" + user + "'@'%' IDENTIFIED BY '" + password + "'");
        } else if (pwdHashingMethod >= 0) {
            // for mysql_native_password, mysql_old_password and sha256_password plugins
            if (!testConn.getSession().versionMeetsMinimum(8, 0, 5)) {
                testStmt.execute("SET @@session.old_passwords = " + pwdHashingMethod);
            }
            testStmt.execute("SET PASSWORD FOR '" + user + "'@'%' = PASSWORD('" + password + "')");
            if (!testConn.getSession().versionMeetsMinimum(8, 0, 5)) {
                testStmt.execute("SET @@session.old_passwords = @@global.old_passwords");
            }
        } else {
            // for cleartext_plugin_server plugin
            dropUser(testStmt, "'" + user + "'@'%'");
            testStmt.execute("CREATE USER '" + user + "'@'%' IDENTIFIED WITH " + pluginName + " AS '" + password + "'");
            testStmt.execute("GRANT ALL ON *.* TO '" + user + "'@'%'");
        }
        testStmt.close();
    } finally {
        if (testConn != null) {
            testConn.close();
        }
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) Properties(java.util.Properties)

Aggregations

JdbcConnection (com.mysql.cj.jdbc.JdbcConnection)280 Properties (java.util.Properties)216 Test (org.junit.jupiter.api.Test)207 Connection (java.sql.Connection)175 MysqlConnection (com.mysql.cj.MysqlConnection)149 XAConnection (javax.sql.XAConnection)100 SQLException (java.sql.SQLException)97 ReplicationConnection (com.mysql.cj.jdbc.ha.ReplicationConnection)96 PooledConnection (javax.sql.PooledConnection)90 MysqlPooledConnection (com.mysql.cj.jdbc.MysqlPooledConnection)81 MysqlXAConnection (com.mysql.cj.jdbc.MysqlXAConnection)79 SuspendableXAConnection (com.mysql.cj.jdbc.SuspendableXAConnection)78 Statement (java.sql.Statement)77 ServerPreparedStatement (com.mysql.cj.jdbc.ServerPreparedStatement)66 PreparedStatement (java.sql.PreparedStatement)66 ResultSet (java.sql.ResultSet)65 ClientPreparedStatement (com.mysql.cj.jdbc.ClientPreparedStatement)60 CommunicationsException (com.mysql.cj.jdbc.exceptions.CommunicationsException)60 IOException (java.io.IOException)54 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)45