Search in sources :

Example 21 with ServerPreparedStatement

use of com.mysql.cj.jdbc.ServerPreparedStatement in project ABC by RuiPinto96274.

the class StatementsTest method testServerPreparedStatementsCaching.

/**
 * WL#11101 - Remove de-cache and close of SSPSs on double call to close()
 *
 * @throws Exception
 */
@Test
public void testServerPreparedStatementsCaching() throws Exception {
    // Non prepared statements must be non-poolable by default.
    assertFalse(this.stmt.isPoolable());
    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;
        }
    };
    Function<Connection, ServerPreparedStatement> getStmtsCacheSingleElem = (c) -> {
        try {
            @SuppressWarnings("unchecked") LRUCache<?, ServerPreparedStatement> stmtsCacheObj = (LRUCache<?, ServerPreparedStatement>) stmtsCacheField.get(c);
            return stmtsCacheObj.get(stmtsCacheObj.keySet().iterator().next());
        } catch (IllegalArgumentException | IllegalAccessException e) {
            fail("Fail getting the statemets cache element.");
            return null;
        }
    };
    final String sql1 = "SELECT 1, ?";
    final String sql2 = "SELECT 2, ?";
    boolean useSPS = false;
    boolean cachePS = false;
    do {
        Properties props = new Properties();
        props.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
        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;
        /*
             * Cache the prepared statement and de-cache it later.
             * (*) if server prepared statement and caching is enabled.
             */
        {
            JdbcConnection testConn = (JdbcConnection) getConnectionWithProps(props);
            PreparedStatement testPstmt = testConn.prepareStatement(sql1);
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            assertTrue(testPstmt.isPoolable());
            // Caches this PS (*).
            testPstmt.close();
            assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // No-op.
            testPstmt.close();
            assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            if (cachedSPS) {
                assertTrue(testPstmt.isPoolable());
                // De-caches this PS; it gets automatically closed (*).
                testPstmt.setPoolable(false);
                assertEquals(0, testConn.getActiveStatementCount());
                assertEquals(0, getStmtsCacheSize.applyAsInt(testConn));
            }
            // No-op.
            testPstmt.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            assertThrows(SQLException.class, "No operations allowed after statement closed\\.", () -> {
                testPstmt.setPoolable(false);
                return null;
            });
            assertThrows(SQLException.class, "No operations allowed after statement closed\\.", () -> {
                testPstmt.isPoolable();
                return null;
            });
            testConn.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
        }
        /*
             * Set not to cache the prepared statement.
             * (*) if server prepared statement and caching is enabled.
             */
        {
            JdbcConnection testConn = (JdbcConnection) getConnectionWithProps(props);
            PreparedStatement testPstmt = testConn.prepareStatement(sql1);
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            assertTrue(testPstmt.isPoolable());
            // Don't cache this PS (*).
            testPstmt.setPoolable(false);
            assertFalse(testPstmt.isPoolable());
            // Doesn't cache this PS (*).
            testPstmt.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // No-op.
            testPstmt.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            assertThrows(SQLException.class, "No operations allowed after statement closed\\.", () -> {
                testPstmt.setPoolable(true);
                return null;
            });
            assertThrows(SQLException.class, "No operations allowed after statement closed\\.", () -> {
                testPstmt.isPoolable();
                return null;
            });
            testConn.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
        }
        /*
             * Set not to cache the prepared statement but change mind before closing it.
             * Reuse the cached prepared statement and don't re-cache it.
             * (*) if server prepared statement and caching is enabled.
             */
        {
            JdbcConnection testConn = (JdbcConnection) getConnectionWithProps(props);
            PreparedStatement testPstmt = testConn.prepareStatement(sql1);
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // Don't cache this PS (*).
            testPstmt.setPoolable(false);
            assertFalse(testPstmt.isPoolable());
            testPstmt.setPoolable(true);
            // Changed my mind, let it be cached (*).
            assertTrue(testPstmt.isPoolable());
            // Caches this PS (*).
            testPstmt.close();
            assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // No-op.
            testPstmt.close();
            assertEquals(cachedSPS ? 1 : 0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            PreparedStatement testPstmtOld = testPstmt;
            // Takes the cached statement (*), or creates a fresh one.
            testPstmt = testConn.prepareStatement(sql1);
            if (cachedSPS) {
                assertSame(testPstmtOld, testPstmt);
            } else {
                assertNotSame(testPstmtOld, testPstmt);
            }
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            assertTrue(testPstmt.isPoolable());
            // Don't cache this PS (*).
            testPstmt.setPoolable(false);
            assertFalse(testPstmt.isPoolable());
            // Doesn't cache this PS (*).
            testPstmt.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            testPstmtOld = testPstmt;
            // Creates a fresh prepared statement.
            testPstmt = testConn.prepareStatement(sql1);
            assertNotSame(testPstmtOld, testPstmt);
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            assertTrue(testPstmt.isPoolable());
            testConn.close();
            assertEquals(0, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
        }
        /*
             * Caching of multiple copies of same prepared statement.
             * (*) if server prepared statement and caching is enabled.
             */
        {
            int psCount = 5;
            JdbcConnection testConn = (JdbcConnection) getConnectionWithProps(props);
            PreparedStatement[] testPstmts = new PreparedStatement[psCount];
            for (int i = 0; i < psCount; i++) {
                testPstmts[i] = testConn.prepareStatement(sql1);
            }
            assertEquals(5, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            for (int i = 0; i < psCount; i++) {
                assertTrue(testPstmts[i].isPoolable());
                // Caches this PS and replaces existing if same (*).
                testPstmts[i].close();
                assertEquals(cachedSPS ? psCount - i : psCount - i - 1, testConn.getActiveStatementCount());
                assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
                if (cachedSPS) {
                    assertSame(testPstmts[i], getStmtsCacheSingleElem.apply(testConn));
                }
            }
            PreparedStatement testPstmt = testConn.prepareStatement(sql1);
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            for (int i = 0; i < psCount; i++) {
                if (cachedSPS && i == psCount - 1) {
                    assertSame(testPstmts[i], testPstmt);
                } else {
                    assertNotSame(testPstmts[i], testPstmt);
                }
            }
            // Don't cache this PS (*).
            testPstmt.setPoolable(false);
            // Doesn't cache this PS (*).
            testPstmt.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));
        }
        /*
             * Combine caching different prepared statements.
             * (*) if server prepared statement and caching is enabled.
             */
        {
            int psCount = 5;
            JdbcConnection testConn = (JdbcConnection) getConnectionWithProps(props);
            PreparedStatement[] testPstmts1 = new PreparedStatement[psCount];
            for (int i = 0; i < psCount; i++) {
                testPstmts1[i] = testConn.prepareStatement(sql1);
            }
            PreparedStatement testPstmt = testConn.prepareStatement(sql2);
            assertEquals(6, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            assertTrue(testPstmt.isPoolable());
            // Caches this PS (*).
            testPstmt.close();
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            for (int i = 0; i < psCount; i++) {
                assertTrue(testPstmts1[i].isPoolable());
                // Caches this PS and replaces existing if same (*).
                testPstmts1[i].close();
                assertEquals(cachedSPS ? psCount - i + 1 : psCount - i - 1, testConn.getActiveStatementCount());
                assertEquals(cachedSPS ? 2 : -1, getStmtsCacheSize.applyAsInt(testConn));
            }
            PreparedStatement testPstmt1 = testConn.prepareStatement(sql1);
            assertEquals(cachedSPS ? 2 : 1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 1 : -1, getStmtsCacheSize.applyAsInt(testConn));
            for (int i = 0; i < psCount; i++) {
                if (cachedSPS && i == psCount - 1) {
                    assertSame(testPstmts1[i], testPstmt1);
                } else {
                    assertNotSame(testPstmts1[i], testPstmt1);
                }
            }
            PreparedStatement testPstmt2 = testConn.prepareStatement(sql2);
            assertEquals(2, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            if (cachedSPS) {
                assertSame(testPstmt, testPstmt2);
            } else {
                assertNotSame(testPstmt, testPstmt2);
            }
            // Don't cache this PS (*).
            testPstmt1.setPoolable(false);
            // Doesn't cache this PS (*).
            testPstmt1.close();
            assertEquals(1, testConn.getActiveStatementCount());
            assertEquals(cachedSPS ? 0 : -1, getStmtsCacheSize.applyAsInt(testConn));
            // Don't cache this PS (*).
            testPstmt2.setPoolable(false);
            // Doesn't cache this PS (*).
            testPstmt2.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));
        }
    } while ((useSPS = !useSPS) || (cachePS = !cachePS));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) BaseTestCase(testsuite.BaseTestCase) Connection(java.sql.Connection) CharArrayReader(java.io.CharArrayReader) Time(java.sql.Time) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) MysqlType(com.mysql.cj.MysqlType) ZonedDateTime(java.time.ZonedDateTime) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) BigDecimal(java.math.BigDecimal) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ByteArrayInputStream(java.io.ByteArrayInputStream) ResultSet(java.sql.ResultSet) LocalTime(java.time.LocalTime) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) CharsetMappingWrapper(com.mysql.cj.CharsetMappingWrapper) NClob(java.sql.NClob) ZoneOffset(java.time.ZoneOffset) OffsetTime(java.time.OffsetTime) MySQLStatementCancelledException(com.mysql.cj.jdbc.exceptions.MySQLStatementCancelledException) Timestamp(java.sql.Timestamp) ParameterBindings(com.mysql.cj.jdbc.ParameterBindings) Reader(java.io.Reader) Assertions.assertNotSame(org.junit.jupiter.api.Assertions.assertNotSame) PreparedStatement(java.sql.PreparedStatement) Test(org.junit.jupiter.api.Test) OffsetDateTime(java.time.OffsetDateTime) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) LocalDate(java.time.LocalDate) CallableStatement(java.sql.CallableStatement) MySQLTimeoutException(com.mysql.cj.jdbc.exceptions.MySQLTimeoutException) ResultSetMetaData(java.sql.ResultSetMetaData) Types(java.sql.Types) Assertions.fail(org.junit.jupiter.api.Assertions.fail) MysqlErrorNumbers(com.mysql.cj.exceptions.MysqlErrorNumbers) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) CountingReBalanceStrategy(testsuite.regression.ConnectionRegressionTest.CountingReBalanceStrategy) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BatchUpdateException(java.sql.BatchUpdateException) LocalDateTime(java.time.LocalDateTime) SimpleDateFormat(java.text.SimpleDateFormat) Callable(java.util.concurrent.Callable) Function(java.util.function.Function) JDBCType(java.sql.JDBCType) SQLException(java.sql.SQLException) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Properties(java.util.Properties) ToIntFunction(java.util.function.ToIntFunction) ConnectionImpl(com.mysql.cj.jdbc.ConnectionImpl) LRUCache(com.mysql.cj.util.LRUCache) ServerStatusDiffInterceptor(com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor) Field(java.lang.reflect.Field) TimeUtil(com.mysql.cj.util.TimeUtil) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) Date(java.sql.Date) AfterEach(org.junit.jupiter.api.AfterEach) StringReader(java.io.StringReader) DateTimeFormatter(java.time.format.DateTimeFormatter) Statement(java.sql.Statement) StringUtils(com.mysql.cj.util.StringUtils) MysqlConnection(com.mysql.cj.MysqlConnection) PropertyKey(com.mysql.cj.conf.PropertyKey) InputStream(java.io.InputStream) SQLException(java.sql.SQLException) Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) Properties(java.util.Properties) Field(java.lang.reflect.Field) LRUCache(com.mysql.cj.util.LRUCache) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) Test(org.junit.jupiter.api.Test)

Example 22 with ServerPreparedStatement

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

the class ResultSetRegressionTest method testBug25650385.

/**
 * Tests fix for BUG#25650385, GETBYTE() RETURNS ERROR FOR BINARY() FLD.
 *
 * @throws Exception
 */
@Test
public void testBug25650385() throws Exception {
    /*
         * getByte (recommended for TINYINT):
         * TINYINT, SMALLINT, INTEGER, BIGINT, REAL, FLOAT, DOUBLE, DECIMAL, NUMERIC, BIT, BOOLEAN, CHAR , VARCHAR , LONGVARCHAR, ROWID
         */
    createTable("testBug25650385", "(b1 blob(12), c1 char(12), c2 binary(12), i1 int, c3 char(12) CHARACTER SET binary)");
    this.stmt.execute("INSERT INTO testBug25650385 values (10, 'a', 48, 10, 23)");
    Properties props = new Properties();
    props.setProperty(PropertyKey.useSSL.getKeyName(), "false");
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    for (boolean useSSPS : new boolean[] { false, true }) {
        for (boolean jdbcCompliantTruncation : new boolean[] { false, true }) {
            props.setProperty(PropertyKey.useServerPrepStmts.getKeyName(), "" + useSSPS);
            props.setProperty(PropertyKey.jdbcCompliantTruncation.getKeyName(), "" + jdbcCompliantTruncation);
            Connection c1 = getConnectionWithProps(props);
            this.pstmt = c1.prepareStatement("select * from testBug25650385");
            if (useSSPS) {
                assertTrue(this.pstmt instanceof ServerPreparedStatement);
            }
            ResultSet rs1 = this.pstmt.executeQuery();
            assertTrue(rs1.next());
            // from blob(12)
            assertEquals('1', rs1.getBytes(1)[0]);
            if (jdbcCompliantTruncation) {
                assertThrows(SQLDataException.class, "Value '10' is outside of valid range for type java.lang.Byte", new Callable<Void>() {

                    public Void call() throws Exception {
                        rs1.getByte(1);
                        return null;
                    }
                });
            } else {
                assertEquals('1', rs1.getByte(1));
            }
            assertEquals(10, rs1.getInt(1));
            assertEquals(10L, rs1.getLong(1));
            assertEquals(10, rs1.getShort(1));
            assertEquals("10", rs1.getString(1));
            // from c1 char(12)
            assertEquals('a', rs1.getBytes(2)[0]);
            assertEquals('a', rs1.getByte(2));
            assertThrows(SQLDataException.class, "Cannot determine value type from string 'a'", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getInt(2);
                    return null;
                }
            });
            assertThrows(SQLDataException.class, "Cannot determine value type from string 'a'", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getLong(2);
                    return null;
                }
            });
            assertThrows(SQLDataException.class, "Cannot determine value type from string 'a'", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getShort(2);
                    return null;
                }
            });
            assertEquals("a", rs1.getString(2));
            // from c2 binary(12)
            assertEquals('4', rs1.getBytes(3)[0]);
            if (jdbcCompliantTruncation) {
                assertThrows(SQLDataException.class, "Value '48.+ is outside of valid range for type java.lang.Byte", new Callable<Void>() {

                    public Void call() throws Exception {
                        rs1.getByte(3);
                        return null;
                    }
                });
            } else {
                assertEquals('4', rs1.getByte(3));
            }
            assertThrows(SQLDataException.class, "Cannot determine value type from string '48.+", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getInt(3);
                    return null;
                }
            });
            assertThrows(SQLDataException.class, "Cannot determine value type from string '48.+", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getLong(3);
                    return null;
                }
            });
            assertThrows(SQLDataException.class, "Cannot determine value type from string '48.+", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getShort(3);
                    return null;
                }
            });
            assertTrue(rs1.getString(3).startsWith("48"));
            // from i1 int
            if (useSSPS) {
                assertEquals(10, rs1.getBytes(4)[0]);
            } else {
                assertEquals('1', rs1.getBytes(4)[0]);
            }
            assertEquals(10, rs1.getByte(4));
            assertEquals(10, rs1.getInt(4));
            assertEquals(10, rs1.getLong(4));
            assertEquals(10, rs1.getShort(4));
            assertEquals("10", rs1.getString(4));
            // from c3 char(12) CHARACTER SET binary
            assertEquals('2', rs1.getBytes(5)[0]);
            if (jdbcCompliantTruncation) {
                assertThrows(SQLDataException.class, "Value '23.+ is outside of valid range for type java.lang.Byte", new Callable<Void>() {

                    public Void call() throws Exception {
                        rs1.getByte(5);
                        return null;
                    }
                });
            } else {
                assertEquals('2', rs1.getByte(5));
            }
            assertThrows(SQLDataException.class, "Cannot determine value type from string '23.+", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getInt(5);
                    return null;
                }
            });
            assertThrows(SQLDataException.class, "Cannot determine value type from string '23.+", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getLong(5);
                    return null;
                }
            });
            assertThrows(SQLDataException.class, "Cannot determine value type from string '23.+", new Callable<Void>() {

                public Void call() throws Exception {
                    rs1.getShort(5);
                    return null;
                }
            });
            assertTrue(rs1.getString(5).startsWith("23"));
        }
    }
}
Also used : Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) ResultSet(java.sql.ResultSet) UpdatableResultSet(com.mysql.cj.jdbc.result.UpdatableResultSet) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) Properties(java.util.Properties) CJCommunicationsException(com.mysql.cj.exceptions.CJCommunicationsException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) SQLDataException(java.sql.SQLDataException) CommunicationsException(com.mysql.cj.jdbc.exceptions.CommunicationsException) Test(org.junit.jupiter.api.Test)

Example 23 with ServerPreparedStatement

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

the class SyntaxRegressionTest method testAlterTableAlgorithmLock.

/**
 * ALTER TABLE syntax changed in 5.6GA
 *
 * ALTER TABLE ... , algorithm, concurrency
 *
 * algorithm:
 * | ALGORITHM [=] DEFAULT
 * | ALGORITHM [=] INPLACE
 * | ALGORITHM [=] COPY
 *
 * concurrency:
 * | LOCK [=] DEFAULT
 * | LOCK [=] NONE
 * | LOCK [=] SHARED
 * | LOCK [=] EXCLUSIVE
 *
 * @throws SQLException
 */
@Test
public void testAlterTableAlgorithmLock() throws SQLException {
    assumeTrue(versionMeetsMinimum(5, 6, 6) && !isServerRunningOnWindows(), "The non-Windows MySQL 5.6.6+ is required to run this test.");
    Connection c = null;
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    props.setProperty(PropertyKey.useServerPrepStmts.getKeyName(), "true");
    try {
        c = getConnectionWithProps(props);
        String[] algs = { "", ", ALGORITHM DEFAULT", ", ALGORITHM = DEFAULT", ", ALGORITHM INPLACE", ", ALGORITHM = INPLACE", ", ALGORITHM COPY", ", ALGORITHM = COPY" };
        String[] lcks = { "", ", LOCK DEFAULT", ", LOCK = DEFAULT", ", LOCK NONE", ", LOCK = NONE", ", LOCK SHARED", ", LOCK = SHARED", ", LOCK EXCLUSIVE", ", LOCK = EXCLUSIVE" };
        createTable("testAlterTableAlgorithmLock", "(x VARCHAR(10) NOT NULL DEFAULT '') CHARSET=latin2");
        int i = 1;
        for (String alg : algs) {
            for (String lck : lcks) {
                i = i ^ 1;
                // We should check if situation change in future
                if (!(lck.contains("NONE") && alg.contains("COPY"))) {
                    String sql = "ALTER TABLE testAlterTableAlgorithmLock CHARSET=latin" + (i + 1) + alg + lck;
                    this.stmt.executeUpdate(sql);
                    this.pstmt = this.conn.prepareStatement("ALTER TABLE testAlterTableAlgorithmLock CHARSET=?" + alg + lck);
                    assertTrue(this.pstmt instanceof ClientPreparedStatement);
                    this.pstmt = c.prepareStatement(sql);
                    assertTrue(this.pstmt instanceof ServerPreparedStatement);
                }
            }
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
}
Also used : ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) Properties(java.util.Properties) Test(org.junit.jupiter.api.Test)

Example 24 with ServerPreparedStatement

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

the class SyntaxRegressionTest method testJsonType.

/**
 * WL#7909 - Server side JSON functions
 *
 * Test support for data type JSON.
 *
 * New JSON functions added in MySQL 5.7.8:
 * - JSON_APPEND(), Append data to JSON document (only in 5.7.8)
 * - JSON_ARRAY_APPEND(), Append data to JSON document (added in 5.7.9+)
 * - JSON_ARRAY_INSERT(), Insert into JSON array
 * - JSON_ARRAY(), Create JSON array
 * - JSON_CONTAINS_PATH(), Whether JSON document contains any data at path
 * - JSON_CONTAINS(), Whether JSON document contains specific object at path
 * - JSON_DEPTH(), Maximum depth of JSON document
 * - JSON_EXTRACT(), Return data from JSON document
 * - JSON_INSERT(), Insert data into JSON document
 * - JSON_KEYS(), Array of keys from JSON document
 * - JSON_LENGTH(), Number of elements in JSON document
 * - JSON_MERGE(), Merge JSON documents (up to 8.0.2)
 * - JSON_MERGE_PRESERVE(), Merge JSON documents (since to 8.0.3)
 * - JSON_OBJECT(), Create JSON object
 * - JSON_QUOTE(), Quote JSON document
 * - JSON_REMOVE(), Remove data from JSON document
 * - JSON_REPLACE(), Replace values in JSON document
 * - JSON_SEARCH(), Path to value within JSON document
 * - JSON_SET(), Insert data into JSON document
 * - JSON_TYPE(), Type of JSON value
 * - JSON_UNQUOTE(), Unquote JSON value
 * - JSON_VALID(), Whether JSON value is valid
 *
 * @throws Exception
 */
@Test
public void testJsonType() throws Exception {
    assumeTrue(versionMeetsMinimum(5, 7, 8), "MySQL 5.7.8+ is required to run this test.");
    createTable("testJsonType", "(id INT PRIMARY KEY, jsonDoc JSON)");
    assertEquals(1, this.stmt.executeUpdate("INSERT INTO testJsonType VALUES (1, '{\"key1\": \"value1\"}')"));
    // Plain statement.
    this.rs = this.stmt.executeQuery("SELECT * FROM testJsonType");
    assertEquals("JSON", this.rs.getMetaData().getColumnTypeName(2));
    assertTrue(this.rs.next());
    assertEquals("{\"key1\": \"value1\"}", this.rs.getString(2));
    assertEquals("{\"key1\": \"value1\"}", this.rs.getObject(2));
    assertFalse(this.rs.next());
    // Updatable ResultSet.
    Statement testStmt = this.conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    this.rs = testStmt.executeQuery("SELECT * FROM testJsonType");
    assertTrue(this.rs.next());
    this.rs.updateString(2, "{\"key1\": \"value1\", \"key2\": \"value2\"}");
    this.rs.updateRow();
    this.rs = testStmt.executeQuery("SELECT * FROM testJsonType");
    assertEquals("JSON", this.rs.getMetaData().getColumnTypeName(2));
    assertTrue(this.rs.next());
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", this.rs.getString(2));
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", this.rs.getObject(2));
    assertFalse(this.rs.next());
    // PreparedStatement.
    this.pstmt = this.conn.prepareStatement("SELECT * FROM testJsonType");
    this.rs = this.pstmt.executeQuery();
    assertEquals("JSON", this.rs.getMetaData().getColumnTypeName(2));
    assertTrue(this.rs.next());
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", this.rs.getString(2));
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", this.rs.getObject(2));
    assertFalse(this.rs.next());
    // ServerPreparedStatement.
    Connection testConn = getConnectionWithProps("useServerPrepStmts=true");
    this.pstmt = testConn.prepareStatement("SELECT * FROM testJsonType");
    this.rs = this.pstmt.executeQuery();
    assertEquals("JSON", this.rs.getMetaData().getColumnTypeName(2));
    assertTrue(this.rs.next());
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", this.rs.getString(2));
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", this.rs.getObject(2));
    assertFalse(this.rs.next());
    testConn.close();
    // CallableStatement.
    createProcedure("testJsonTypeProc", "(OUT jsonDoc JSON) SELECT t.jsonDoc INTO jsonDoc FROM testJsonType t");
    CallableStatement testCstmt = this.conn.prepareCall("{CALL testJsonTypeProc(?)}");
    testCstmt.registerOutParameter(1, Types.CHAR);
    testCstmt.execute();
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", testCstmt.getString(1));
    assertEquals("{\"key1\": \"value1\", \"key2\": \"value2\"}", testCstmt.getObject(1));
    // JSON functions.
    testJsonTypeCheckFunction(versionMeetsMinimum(5, 7, 9) ? "SELECT JSON_ARRAY_APPEND('[1]', '$', 2)" : "SELECT JSON_APPEND('[1]', '$', 2)", "[1, 2]");
    testJsonTypeCheckFunction("SELECT JSON_ARRAY_INSERT('[2]', '$[0]', 1)", "[1, 2]");
    testJsonTypeCheckFunction("SELECT JSON_ARRAY(1, 2)", "[1, 2]");
    testJsonTypeCheckFunction("SELECT JSON_CONTAINS_PATH('{\"a\": 1}', 'one', '$.a')", "1");
    testJsonTypeCheckFunction("SELECT JSON_CONTAINS('{\"a\": 1}', '1', '$.a')", "1");
    testJsonTypeCheckFunction("SELECT JSON_DEPTH('{\"a\": 1}')", "2");
    testJsonTypeCheckFunction("SELECT JSON_EXTRACT('[1, 2]', '$[0]')", "1");
    testJsonTypeCheckFunction("SELECT JSON_INSERT('[1]', '$[1]', 2)", "[1, 2]");
    testJsonTypeCheckFunction("SELECT JSON_KEYS('{\"a\": 1}')", "[\"a\"]");
    testJsonTypeCheckFunction("SELECT JSON_LENGTH('{\"a\": 1}')", "1");
    testJsonTypeCheckFunction(versionMeetsMinimum(8, 0, 3) ? "SELECT JSON_MERGE_PRESERVE('[1]', '[2]')" : "SELECT JSON_MERGE('[1]', '[2]')", "[1, 2]");
    testJsonTypeCheckFunction("SELECT JSON_OBJECT('a', 1)", "{\"a\": 1}");
    testJsonTypeCheckFunction("SELECT JSON_QUOTE('[1]')", "\"[1]\"");
    testJsonTypeCheckFunction("SELECT JSON_REMOVE('[1, 2]', '$[1]')", "[1]");
    testJsonTypeCheckFunction("SELECT JSON_REPLACE('[0]', '$[0]', 1)", "[1]");
    testJsonTypeCheckFunction("SELECT JSON_SEARCH('{\"a\": \"1\"}', 'one', '1')", "\"$.a\"");
    testJsonTypeCheckFunction("SELECT JSON_SET('[1, 1]', '$[1]', 2)", "[1, 2]");
    testJsonTypeCheckFunction("SELECT JSON_TYPE('[]')", "ARRAY");
    testJsonTypeCheckFunction("SELECT JSON_UNQUOTE('\"[1]\"')", "[1]");
    testJsonTypeCheckFunction("SELECT JSON_VALID('{\"a\": 1}')", "1");
}
Also used : ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) CallableStatement(java.sql.CallableStatement) Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) Test(org.junit.jupiter.api.Test)

Example 25 with ServerPreparedStatement

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

the class SyntaxRegressionTest method testExplicitPartitions.

/**
 * Test for explicit partition selection syntax
 *
 * @throws Exception
 */
@Test
public void testExplicitPartitions() throws Exception {
    assumeTrue(versionMeetsMinimum(5, 6, 5) && isMysqlRunningLocally(), "Locally running MySQL 5.6.5+ is required to perform this test.");
    String datadir = null;
    this.rs = this.stmt.executeQuery("SHOW VARIABLES WHERE Variable_name='datadir'");
    this.rs.next();
    datadir = this.rs.getString(2);
    if (datadir != null) {
        datadir = new File(datadir).getCanonicalPath();
    }
    this.rs = this.stmt.executeQuery("SHOW VARIABLES WHERE Variable_name='secure_file_priv'");
    this.rs.next();
    String fileprivdir = this.rs.getString(2);
    assumeFalse("NULL".equalsIgnoreCase(this.rs.getString(2)), "To run this test the server needs to be started with the option\"--secure-file-priv=\"");
    if (fileprivdir.length() > 0) {
        fileprivdir = new File(fileprivdir).getCanonicalPath();
        assumeTrue(datadir.equals(fileprivdir), "To run this test the server option\"--secure-file-priv=\" needs to be empty or to match the server's data directory.");
    }
    Properties props = getPropertiesFromTestsuiteUrl();
    String dbname = props.getProperty(PropertyKey.DBNAME.getKeyName());
    props = new Properties();
    props.setProperty(PropertyKey.useServerPrepStmts.getKeyName(), "true");
    Connection c = null;
    try {
        this.stmt.executeUpdate("SET @old_default_storage_engine = @@default_storage_engine");
        this.stmt.executeUpdate("SET @@default_storage_engine = 'InnoDB'");
        c = getConnectionWithProps(props);
        createTable("testExplicitPartitions", "(a INT NOT NULL, b varchar (64), INDEX (b,a), PRIMARY KEY (a)) ENGINE = InnoDB" + " PARTITION BY RANGE (a) SUBPARTITION BY HASH (a) SUBPARTITIONS 2" + " (PARTITION pNeg VALUES LESS THAN (0) (SUBPARTITION subp0, SUBPARTITION subp1)," + " PARTITION `p0-9` VALUES LESS THAN (10) (SUBPARTITION subp2, SUBPARTITION subp3)," + " PARTITION `p10-99` VALUES LESS THAN (100) (SUBPARTITION subp4, SUBPARTITION subp5)," + " PARTITION `p100-99999` VALUES LESS THAN (100000) (SUBPARTITION subp6, SUBPARTITION subp7))");
        this.stmt.executeUpdate("INSERT INTO testExplicitPartitions PARTITION (pNeg, pNeg) VALUES (-1, \"pNeg(-subp1)\")");
        this.pstmt = this.conn.prepareStatement("INSERT INTO testExplicitPartitions PARTITION (pNeg, subp0) VALUES (-3, \"pNeg(-subp1)\")");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("INSERT INTO testExplicitPartitions PARTITION (pNeg, subp0) VALUES (-2, \"(pNeg-)subp0\")");
        assertTrue(this.pstmt instanceof com.mysql.cj.jdbc.ServerPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("INSERT INTO testExplicitPartitions PARTITION (`p100-99999`) VALUES (100, \"`p100-99999`(-subp6)\"), (101, \"`p100-99999`(-subp7)\"), (1000, \"`p100-99999`(-subp6)\")");
        assertTrue(this.pstmt instanceof com.mysql.cj.jdbc.ServerPreparedStatement);
        this.pstmt.execute();
        this.stmt.executeUpdate("INSERT INTO testExplicitPartitions PARTITION(`p10-99`,subp3) VALUES (1, \"subp3\"), (10, \"p10-99\")");
        this.stmt.executeUpdate("INSERT INTO testExplicitPartitions PARTITION(subp3) VALUES (3, \"subp3\")");
        this.stmt.executeUpdate("INSERT INTO testExplicitPartitions PARTITION(`p0-9`) VALUES (5, \"p0-9:subp3\")");
        this.stmt.executeUpdate("FLUSH STATUS");
        this.stmt.execute("SELECT * FROM testExplicitPartitions PARTITION (subp2)");
        this.pstmt = this.conn.prepareStatement("SELECT * FROM testExplicitPartitions PARTITION (subp2,pNeg) AS TableAlias");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("SELECT * FROM testExplicitPartitions PARTITION (subp2,pNeg) AS TableAlias");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.pstmt = this.conn.prepareStatement("LOCK TABLE testExplicitPartitions READ, testExplicitPartitions as TableAlias READ");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("LOCK TABLE testExplicitPartitions READ, testExplicitPartitions as TableAlias READ");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = this.conn.prepareStatement("SELECT * FROM testExplicitPartitions PARTITION (subp3) AS TableAlias");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("SELECT COUNT(*) FROM testExplicitPartitions PARTITION (`p10-99`)");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.pstmt.execute();
        this.pstmt = this.conn.prepareStatement("SELECT * FROM testExplicitPartitions PARTITION (pNeg) WHERE a = 100");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("SELECT * FROM testExplicitPartitions PARTITION (pNeg) WHERE a = 100");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.pstmt.execute();
        this.stmt.executeUpdate("UNLOCK TABLES");
        // Test LOAD
        assertNotNull(dbname, "No database selected");
        File f = new File(datadir + File.separator + dbname + File.separator + "loadtestExplicitPartitions.txt");
        if (f.exists()) {
            f.delete();
        }
        this.pstmt = this.conn.prepareStatement("SELECT * FROM testExplicitPartitions PARTITION (pNeg, `p10-99`) INTO OUTFILE 'loadtestExplicitPartitions.txt'");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("SELECT * FROM testExplicitPartitions PARTITION (pNeg, `p10-99`) INTO OUTFILE 'loadtestExplicitPartitions.txt'");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.stmt.execute("SELECT * FROM testExplicitPartitions PARTITION (pNeg, `p10-99`) INTO OUTFILE 'loadtestExplicitPartitions.txt'");
        this.pstmt = this.conn.prepareStatement("ALTER TABLE testExplicitPartitions TRUNCATE PARTITION pNeg, `p10-99`");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("ALTER TABLE testExplicitPartitions TRUNCATE PARTITION pNeg, `p10-99`");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.stmt.executeUpdate("ALTER TABLE testExplicitPartitions TRUNCATE PARTITION pNeg, `p10-99`");
        this.stmt.executeUpdate("FLUSH STATUS");
        this.pstmt = this.conn.prepareStatement("LOAD DATA INFILE 'loadtestExplicitPartitions.txt' INTO TABLE testExplicitPartitions PARTITION (pNeg, subp4, subp5)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("LOAD DATA INFILE 'loadtestExplicitPartitions.txt' INTO TABLE testExplicitPartitions PARTITION (pNeg, subp4, subp5)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.stmt.executeUpdate("LOAD DATA INFILE 'loadtestExplicitPartitions.txt' INTO TABLE testExplicitPartitions PARTITION (pNeg, subp4, subp5)");
        this.stmt.executeUpdate("ALTER TABLE testExplicitPartitions TRUNCATE PARTITION pNeg, `p10-99`");
        this.stmt.executeUpdate("FLUSH STATUS");
        this.pstmt = this.conn.prepareStatement("LOAD DATA INFILE 'loadtestExplicitPartitions.txt' INTO TABLE testExplicitPartitions PARTITION (pNeg, `p10-99`)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("LOAD DATA INFILE 'loadtestExplicitPartitions.txt' INTO TABLE testExplicitPartitions PARTITION (pNeg, `p10-99`)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.stmt.executeUpdate("LOCK TABLE testExplicitPartitions WRITE");
        this.stmt.executeUpdate("LOAD DATA INFILE 'loadtestExplicitPartitions.txt' INTO TABLE testExplicitPartitions PARTITION (pNeg, `p10-99`)");
        this.stmt.executeUpdate("UNLOCK TABLES");
        // Test UPDATE
        this.stmt.executeUpdate("UPDATE testExplicitPartitions PARTITION(subp0) SET b = concat(b, ', Updated')");
        this.pstmt = this.conn.prepareStatement("UPDATE testExplicitPartitions PARTITION(subp0) SET b = concat(b, ', Updated2') WHERE a = -2");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("UPDATE testExplicitPartitions PARTITION(subp0) SET a = -4, b = concat(b, ', Updated from a = -2') WHERE a = -2");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.pstmt.execute();
        this.stmt.executeUpdate("UPDATE testExplicitPartitions PARTITION(subp0) SET b = concat(b, ', Updated2') WHERE a = 100");
        this.stmt.executeUpdate("UPDATE testExplicitPartitions PARTITION(subp0) SET a = -2, b = concat(b, ', Updated from a = 100') WHERE a = 100");
        this.pstmt = this.conn.prepareStatement("UPDATE testExplicitPartitions PARTITION(`p100-99999`, pNeg) SET a = -222, b = concat(b, ', Updated from a = 100') WHERE a = 100");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("UPDATE testExplicitPartitions SET b = concat(b, ', Updated2') WHERE a = 1000000");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.pstmt.execute();
        // Test DELETE
        this.stmt.executeUpdate("DELETE FROM testExplicitPartitions PARTITION (pNeg) WHERE a = -1");
        this.pstmt = this.conn.prepareStatement("DELETE FROM testExplicitPartitions PARTITION (pNeg) WHERE a = -1");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("DELETE FROM testExplicitPartitions PARTITION (pNeg) WHERE a = -1");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.pstmt.execute();
        this.stmt.executeUpdate("DELETE FROM testExplicitPartitions PARTITION (subp1) WHERE b like '%subp1%'");
        this.pstmt = this.conn.prepareStatement("DELETE FROM testExplicitPartitions PARTITION (subp1) WHERE b like '%subp1%'");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt.execute();
        this.pstmt = c.prepareStatement("DELETE FROM testExplicitPartitions PARTITION (subp1) WHERE b like '%subp1%'");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.pstmt.execute();
        this.stmt.executeUpdate("FLUSH STATUS");
        this.stmt.executeUpdate("LOCK TABLE testExplicitPartitions WRITE");
        this.stmt.executeUpdate("DELETE FROM testExplicitPartitions PARTITION (subp1) WHERE b = 'p0-9:subp3'");
        this.pstmt = this.conn.prepareStatement("DELETE FROM testExplicitPartitions PARTITION (subp1) WHERE b = 'p0-9:subp3'");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.stmt.executeUpdate("DELETE FROM testExplicitPartitions PARTITION (`p0-9`) WHERE b = 'p0-9:subp3'");
        this.pstmt = this.conn.prepareStatement("DELETE FROM testExplicitPartitions PARTITION (`p0-9`) WHERE b = 'p0-9:subp3'");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.stmt.executeUpdate("UNLOCK TABLES");
        // Test multi-table DELETE
        this.stmt.executeUpdate("CREATE TABLE testExplicitPartitions2 LIKE testExplicitPartitions");
        this.pstmt = this.conn.prepareStatement("INSERT INTO testExplicitPartitions2 PARTITION (`p10-99`, subp3, `p100-99999`) SELECT * FROM testExplicitPartitions PARTITION (subp3, `p10-99`, `p100-99999`)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("INSERT INTO testExplicitPartitions2 PARTITION (`p10-99`, subp3, `p100-99999`) SELECT * FROM testExplicitPartitions PARTITION (subp3, `p10-99`, `p100-99999`)");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.stmt.executeUpdate("INSERT INTO testExplicitPartitions2 PARTITION (`p10-99`, subp3, `p100-99999`) SELECT * FROM testExplicitPartitions PARTITION (subp3, `p10-99`, `p100-99999`)");
        this.stmt.executeUpdate("ALTER TABLE testExplicitPartitions2 TRUNCATE PARTITION `p10-99`, `p0-9`, `p100-99999`");
        this.pstmt = this.conn.prepareStatement("INSERT IGNORE INTO testExplicitPartitions2 PARTITION (subp3) SELECT * FROM testExplicitPartitions PARTITION (subp3, `p10-99`, `p100-99999`)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("INSERT IGNORE INTO testExplicitPartitions2 PARTITION (subp3) SELECT * FROM testExplicitPartitions PARTITION (subp3, `p10-99`, `p100-99999`)");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.stmt.executeUpdate("INSERT IGNORE INTO testExplicitPartitions2 PARTITION (subp3) SELECT * FROM testExplicitPartitions PARTITION (subp3, `p10-99`, `p100-99999`)");
        this.stmt.executeUpdate("TRUNCATE TABLE testExplicitPartitions2");
        this.stmt.executeUpdate("INSERT INTO testExplicitPartitions2 SELECT * FROM testExplicitPartitions PARTITION (subp3, `p10-99`, `p100-99999`)");
        this.pstmt = this.conn.prepareStatement("CREATE TABLE testExplicitPartitions3 SELECT * FROM testExplicitPartitions PARTITION (pNeg,subp3,`p100-99999`)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("CREATE TABLE testExplicitPartitions3 SELECT * FROM testExplicitPartitions PARTITION (pNeg,subp3,`p100-99999`)");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.stmt.executeUpdate("CREATE TABLE testExplicitPartitions3 SELECT * FROM testExplicitPartitions PARTITION (pNeg,subp3,`p100-99999`)");
        this.pstmt = this.conn.prepareStatement("DELETE testExplicitPartitions, testExplicitPartitions2 FROM testExplicitPartitions PARTITION (pNeg), testExplicitPartitions3, testExplicitPartitions2 PARTITION (subp3) WHERE testExplicitPartitions.a = testExplicitPartitions3.a AND testExplicitPartitions3.b = 'subp3' AND testExplicitPartitions3.a = testExplicitPartitions2.a");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("DELETE testExplicitPartitions, testExplicitPartitions2 FROM testExplicitPartitions PARTITION (pNeg), testExplicitPartitions3, testExplicitPartitions2 PARTITION (subp3) WHERE testExplicitPartitions.a = testExplicitPartitions3.a AND testExplicitPartitions3.b = 'subp3' AND testExplicitPartitions3.a = testExplicitPartitions2.a");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.stmt.executeUpdate("DELETE testExplicitPartitions, testExplicitPartitions2 FROM testExplicitPartitions PARTITION (pNeg), testExplicitPartitions3, testExplicitPartitions2 PARTITION (subp3) WHERE testExplicitPartitions.a = testExplicitPartitions3.a AND testExplicitPartitions3.b = 'subp3' AND testExplicitPartitions3.a = testExplicitPartitions2.a");
        this.pstmt = this.conn.prepareStatement("DELETE FROM testExplicitPartitions2, testExplicitPartitions3 USING testExplicitPartitions2 PARTITION (`p0-9`), testExplicitPartitions3, testExplicitPartitions PARTITION (subp3) WHERE testExplicitPartitions.a = testExplicitPartitions3.a AND testExplicitPartitions3.b = 'subp3' AND testExplicitPartitions2.a = testExplicitPartitions.a");
        assertTrue(this.pstmt instanceof ClientPreparedStatement);
        this.pstmt = c.prepareStatement("DELETE FROM testExplicitPartitions2, testExplicitPartitions3 USING testExplicitPartitions2 PARTITION (`p0-9`), testExplicitPartitions3, testExplicitPartitions PARTITION (subp3) WHERE testExplicitPartitions.a = testExplicitPartitions3.a AND testExplicitPartitions3.b = 'subp3' AND testExplicitPartitions2.a = testExplicitPartitions.a");
        assertTrue(this.pstmt instanceof ServerPreparedStatement);
        this.stmt.executeUpdate("DELETE FROM testExplicitPartitions2, testExplicitPartitions3 USING testExplicitPartitions2 PARTITION (`p0-9`), testExplicitPartitions3, testExplicitPartitions PARTITION (subp3) WHERE testExplicitPartitions.a = testExplicitPartitions3.a AND testExplicitPartitions3.b = 'subp3' AND testExplicitPartitions2.a = testExplicitPartitions.a");
        this.stmt.executeUpdate("SET @@default_storage_engine = @old_default_storage_engine");
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testExplicitPartitions, testExplicitPartitions2, testExplicitPartitions3");
        if (c != null) {
            c.close();
        }
        if (datadir != null) {
            File f = new File(datadir + File.separator + dbname + File.separator + "loadtestExplicitPartitions.txt");
            if (f.exists()) {
                f.deleteOnExit();
            }
        }
    }
}
Also used : ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) Properties(java.util.Properties) File(java.io.File) Test(org.junit.jupiter.api.Test)

Aggregations

JdbcConnection (com.mysql.cj.jdbc.JdbcConnection)30 ServerPreparedStatement (com.mysql.cj.jdbc.ServerPreparedStatement)30 Connection (java.sql.Connection)30 Test (org.junit.jupiter.api.Test)30 ClientPreparedStatement (com.mysql.cj.jdbc.ClientPreparedStatement)24 Properties (java.util.Properties)24 MysqlConnection (com.mysql.cj.MysqlConnection)21 PreparedStatement (java.sql.PreparedStatement)21 CallableStatement (java.sql.CallableStatement)18 Statement (java.sql.Statement)18 JdbcPreparedStatement (com.mysql.cj.jdbc.JdbcPreparedStatement)12 ReplicationConnection (com.mysql.cj.jdbc.ha.ReplicationConnection)12 XAConnection (javax.sql.XAConnection)12 StatementsTest (testsuite.simple.StatementsTest)12 JdbcStatement (com.mysql.cj.jdbc.JdbcStatement)9 ResultSet (java.sql.ResultSet)9 SQLException (java.sql.SQLException)9 CharsetMappingWrapper (com.mysql.cj.CharsetMappingWrapper)6 DatabaseTerm (com.mysql.cj.conf.PropertyDefinitions.DatabaseTerm)6 PropertyKey (com.mysql.cj.conf.PropertyKey)6