From 08779406c5c9b78128fe7fddc86a57e79643c43d Mon Sep 17 00:00:00 2001 From: rusher Date: Sun, 18 Oct 2020 21:59:30 +0200 Subject: [PATCH 01/25] set 2.7.1 SNAPSHOT version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 327aa3322..461ab6975 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,7 @@ mariadb-java-client jar mariadb-java-client - 2.7.0 + 2.7.1-SNAPSHOT JDBC driver for MariaDB and MySQL https://mariadb.com/kb/en/mariadb/about-mariadb-connector-j/ From 1646a5ff87c617d29ed75fe0dd621a829faae60c Mon Sep 17 00:00:00 2001 From: rusher Date: Sun, 18 Oct 2020 22:04:38 +0200 Subject: [PATCH 02/25] [misc] small simplification of MariaXaResource XID generation --- .../org/mariadb/jdbc/MariaXaResource.java | 2 +- .../org/mariadb/jdbc/internal/util/Utils.java | 22 ------------------- .../jdbc/DistributedTransactionTest.java | 6 ----- .../org/mariadb/jdbc/MariaXaResourceTest.java | 8 +++---- .../mariadb/jdbc/internal/util/UtilsTest.java | 8 ------- 5 files changed, 5 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/mariadb/jdbc/MariaXaResource.java b/src/main/java/org/mariadb/jdbc/MariaXaResource.java index 54e9475e4..220b880cf 100644 --- a/src/main/java/org/mariadb/jdbc/MariaXaResource.java +++ b/src/main/java/org/mariadb/jdbc/MariaXaResource.java @@ -74,7 +74,7 @@ protected static String xidToString(Xid xid) { + ",0x" + Utils.byteArrayToHexString(xid.getBranchQualifier()) + ",0x" - + Utils.intToHexString(xid.getFormatId()); + + Integer.toHexString(xid.getFormatId()); } private static String flagsToString(int flags) { diff --git a/src/main/java/org/mariadb/jdbc/internal/util/Utils.java b/src/main/java/org/mariadb/jdbc/internal/util/Utils.java index 9d35b1fab..0d4102505 100644 --- a/src/main/java/org/mariadb/jdbc/internal/util/Utils.java +++ b/src/main/java/org/mariadb/jdbc/internal/util/Utils.java @@ -850,28 +850,6 @@ public static String byteArrayToHexString(final byte[] bytes) { return (bytes != null) ? getHex(bytes) : ""; } - /** - * Convert int value to hexadecimal String. - * - * @param value value to transform - * @return Hexadecimal String value of integer. - */ - public static String intToHexString(final int value) { - final StringBuilder hex = new StringBuilder(8); - int offset = 24; - byte b; - boolean nullEnd = false; - while (offset >= 0) { - b = (byte) (value >> offset); - offset -= 8; - if (b != 0 || nullEnd) { - nullEnd = true; - hex.append(hexArray[(b & 0xF0) >> 4]).append(hexArray[(b & 0x0F)]); - } - } - return hex.toString(); - } - /** * Parse the option "sessionVariable" to ensure having no injection. semi-column not in string * will be replaced by comma. diff --git a/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java b/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java index 674091924..30b0314c9 100644 --- a/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java +++ b/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java @@ -63,7 +63,6 @@ import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.junit.Assume; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -87,11 +86,6 @@ public static void initClass() throws SQLException { createTable("xatable", "i int", "ENGINE=InnoDB"); } - @Before - public void checkSupported() throws SQLException { - requireMinimumVersion(5, 0); - } - private Xid newXid() { return new MariaDbXid( 1, UUID.randomUUID().toString().getBytes(), UUID.randomUUID().toString().getBytes()); diff --git a/src/test/java/org/mariadb/jdbc/MariaXaResourceTest.java b/src/test/java/org/mariadb/jdbc/MariaXaResourceTest.java index 126301db8..ca5c0c611 100644 --- a/src/test/java/org/mariadb/jdbc/MariaXaResourceTest.java +++ b/src/test/java/org/mariadb/jdbc/MariaXaResourceTest.java @@ -9,14 +9,14 @@ public class MariaXaResourceTest extends BaseTest { @Test public void xidToString() { assertEquals( - "0x00,0x01,0x05", - MariaXaResource.xidToString(new MariaDbXid(5, new byte[] {0x00}, new byte[] {0x01}))); + "0x00,0x01,0x627", + MariaXaResource.xidToString(new MariaDbXid(1575, new byte[] {0x00}, new byte[] {0x01}))); assertEquals( - "0x,0x000100,0x0400", + "0x,0x000100,0x400", MariaXaResource.xidToString( new MariaDbXid(1024, new byte[] {}, new byte[] {0x00, 0x01, 0x00}))); assertEquals( - "0x00,0x000100,0xC3C20186", + "0x00,0x000100,0xc3c20186", MariaXaResource.xidToString( new MariaDbXid(-1010695802, new byte[] {0x00}, new byte[] {0x00, 0x01, 0x00}))); } diff --git a/src/test/java/org/mariadb/jdbc/internal/util/UtilsTest.java b/src/test/java/org/mariadb/jdbc/internal/util/UtilsTest.java index 2e3d5ebfb..33ca804fb 100644 --- a/src/test/java/org/mariadb/jdbc/internal/util/UtilsTest.java +++ b/src/test/java/org/mariadb/jdbc/internal/util/UtilsTest.java @@ -148,12 +148,4 @@ public void localLocalParsing() { assertFalse( Utils.validateFileName("LOAD DATA INFILE ? /**/", goodParameterHolders, "file_name")); } - - @Test - public void intToHexString() { - assertEquals("05", Utils.intToHexString(5)); - assertEquals("0400", Utils.intToHexString(1024)); - assertEquals("C3C20186", Utils.intToHexString(-1010695802)); - assertEquals("FFFFFFFF", Utils.intToHexString(-1)); - } } From 5c9d7fe9c7dd1fdfdf54c01e962b9aaee7f5568a Mon Sep 17 00:00:00 2001 From: rusher Date: Sun, 18 Oct 2020 22:19:07 +0200 Subject: [PATCH 03/25] [CONJ-834] use of BULK is conditionned to server 10.2.7+ version, not capability use of BULK is conditionned to server 10.2.7+ version, not MARIADB_CLIENT_STMT_BULK_OPERATIONS capability. This can cause issues when using with proxy like maxscale. --- .../mariadb/jdbc/internal/MariaDbServerCapabilities.java | 6 ++++++ .../jdbc/internal/protocol/AbstractConnectProtocol.java | 7 +++++++ .../jdbc/internal/protocol/AbstractQueryProtocol.java | 7 +++---- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/mariadb/jdbc/internal/MariaDbServerCapabilities.java b/src/main/java/org/mariadb/jdbc/internal/MariaDbServerCapabilities.java index 7c53058d1..44afaed9e 100644 --- a/src/main/java/org/mariadb/jdbc/internal/MariaDbServerCapabilities.java +++ b/src/main/java/org/mariadb/jdbc/internal/MariaDbServerCapabilities.java @@ -89,4 +89,10 @@ public class MariaDbServerCapabilities { 1L << 32; /* Client support progress indicator (since 10.2) */ public static final long MARIADB_CLIENT_COM_MULTI = 1L << 33; /* bundle command during connection */ + + /* support of array binding */ + public static final long MARIADB_CLIENT_STMT_BULK_OPERATIONS = 1L << 34; + + /* support of extended metadata (e.g. type/format information) */ + public static final long MARIADB_CLIENT_EXTENDED_METADATA = 1L << 35; } diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java index 993a21a6b..cab8612b6 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java @@ -293,6 +293,13 @@ private static long initializeClientCapabilities( capabilities |= MariaDbServerCapabilities.CLIENT_DEPRECATE_EOF; } + if (options.useBulkStmts) { + if ((serverCapabilities & MariaDbServerCapabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS) + != 0) { + capabilities |= MariaDbServerCapabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS; + } + } + if (options.useCompression) { if ((serverCapabilities & MariaDbServerCapabilities.COMPRESS) == 0) { // ensure that server has compress capacity - MaxScale doesn't diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java index 020126887..5440264cc 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java @@ -407,7 +407,6 @@ public boolean executeBatchClient( && !hasLongData && prepareResult.isQueryMultipleRewritable() // INSERT FROM SELECT not allowed && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS - && versionGreaterOrEqual(10, 2, 7) && executeBulkBatch(results, prepareResult.getSql(), null, parametersList)) { return true; } @@ -422,7 +421,6 @@ && executeBulkBatch(results, prepareResult.getSql(), null, parametersList)) { if (options.useBulkStmts && !hasLongData && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS - && versionGreaterOrEqual(10, 2, 7) && executeBulkBatch(results, prepareResult.getSql(), null, parametersList)) { return true; } @@ -455,11 +453,13 @@ private boolean executeBulkBatch( // ************************************************************************************** // Ensure BULK can be use : - // - server version >= 10.2.7 + // - server support bulk // - no stream // - parameter type doesn't change // - avoid INSERT FROM SELECT // ************************************************************************************** + if ((serverCapabilities & MariaDbServerCapabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS) == 0) + return false; // ensure that there is no long data and type doesn't change ParameterHolder[] initParameters = parametersList.get(0); @@ -1009,7 +1009,6 @@ public boolean executeBatchServer( if (options.useBulkStmts && !hasLongData && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS - && versionGreaterOrEqual(10, 2, 7) && executeBulkBatch(results, sql, serverPrepareResult, parametersList)) { return true; } From b84c27de06cf774b03f794538dfd95393ccc8b72 Mon Sep 17 00:00:00 2001 From: rusher Date: Sun, 18 Oct 2020 23:05:06 +0200 Subject: [PATCH 04/25] [misc] appveyor server msi retrival, follow redirection --- appveyor-download.bat | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/appveyor-download.bat b/appveyor-download.bat index fc12a609e..5cc2dbbb3 100644 --- a/appveyor-download.bat +++ b/appveyor-download.bat @@ -2,12 +2,11 @@ set archive=http://ftp.hosteurope.de/mirror/archive.mariadb.org//mariadb-%DB%/winx64-packages/mariadb-%DB%-winx64.msi set last=http://mirror.i3d.net/pub/mariadb//mariadb-%DB%/winx64-packages/mariadb-%DB%-winx64.msi -curl -fsS -o server.msi %archive% +curl -fLsS -o server.msi %archive% if %ERRORLEVEL% == 0 goto end - -curl -fsS -o server.msi %last% +curl -fLsS -o server.msi %last% if %ERRORLEVEL% == 0 goto end echo Failure Reason Given is %errorlevel% From 15af61a6280006aad58cd2b8c0eaf776cbff2041 Mon Sep 17 00:00:00 2001 From: rusher Date: Sun, 18 Oct 2020 23:07:26 +0200 Subject: [PATCH 05/25] [misc] junit version bump --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 461ab6975..c1d37b5a7 100644 --- a/pom.xml +++ b/pom.xml @@ -257,7 +257,7 @@ junit junit - 4.13 + 4.13.1 test From efb19400e6bc3c707de9cf00291a49ed732c6ec0 Mon Sep 17 00:00:00 2001 From: rusher Date: Fri, 6 Nov 2020 14:29:54 +0100 Subject: [PATCH 06/25] [CONJ-837] prepared statement cache leak on Resultset CONCUR_UPDATABLE concurrency --- .../read/resultset/UpdatableResultSet.java | 57 ++++++++++--------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/UpdatableResultSet.java b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/UpdatableResultSet.java index 21e4bd833..5b75831e6 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/UpdatableResultSet.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/UpdatableResultSet.java @@ -1119,39 +1119,39 @@ public void insertRow() throws SQLException { insertSql.append(" RETURNING ").append(returningClause); } - BasePrepareStatement insertPreparedStatement = + try (BasePrepareStatement insertPreparedStatement = (row instanceof BinaryRowProtocol) ? connection.serverPrepareStatement(insertSql.toString()) - : connection.clientPrepareStatement(insertSql.toString()); + : connection.clientPrepareStatement(insertSql.toString())) { - for (Map.Entry entry : paramMap.entrySet()) { - insertPreparedStatement.setParameter(entry.getKey(), entry.getValue()); - } - - ResultSet insertRs = insertPreparedStatement.executeQuery(); - if (connection.isServerMariaDb() && connection.versionGreaterOrEqual(10, 5, 1)) { - if (insertRs.next()) { - byte[] rowByte = ((SelectResultSet) insertRs).getCurrentRowData(); - addRowData(rowByte); + for (Map.Entry entry : paramMap.entrySet()) { + insertPreparedStatement.setParameter(entry.getKey(), entry.getValue()); } - } else if (hasGeneratedPrimaryFields) { - // primary is auto_increment (only one field) - ResultSet rsKey = insertPreparedStatement.getGeneratedKeys(); - if (rsKey.next()) { - - prepareRefreshStmt(); - refreshPreparedStatement.setObject(1, rsKey.getObject(1), generatedSqlType); - SelectResultSet rs = (SelectResultSet) refreshPreparedStatement.executeQuery(); - - // update row data only if not deleted externally - if (rs.next()) { - addRowData(rs.getCurrentRowData()); + + ResultSet insertRs = insertPreparedStatement.executeQuery(); + if (connection.isServerMariaDb() && connection.versionGreaterOrEqual(10, 5, 1)) { + if (insertRs.next()) { + byte[] rowByte = ((SelectResultSet) insertRs).getCurrentRowData(); + addRowData(rowByte); + } + } else if (hasGeneratedPrimaryFields) { + // primary is auto_increment (only one field) + ResultSet rsKey = insertPreparedStatement.getGeneratedKeys(); + if (rsKey.next()) { + + prepareRefreshStmt(); + refreshPreparedStatement.setObject(1, rsKey.getObject(1), generatedSqlType); + SelectResultSet rs = (SelectResultSet) refreshPreparedStatement.executeQuery(); + + // update row data only if not deleted externally + if (rs.next()) { + addRowData(rs.getCurrentRowData()); + } } + } else { + addRowData(refreshRawData()); } - } else { - addRowData(refreshRawData()); } - Arrays.fill(parameterHolders, null); } } @@ -1468,4 +1468,9 @@ public boolean previous() throws SQLException { } return super.previous(); } + + public void close() throws SQLException { + refreshPreparedStatement.close(); + super.close(); + } } From 49f3d2a31a4ee0f6390c736c58b9b39b2337a351 Mon Sep 17 00:00:00 2001 From: rusher Date: Fri, 6 Nov 2020 23:15:04 +0100 Subject: [PATCH 07/25] [misc] permit providing test parameter from System properties --- src/test/java/org/mariadb/jdbc/BaseTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/org/mariadb/jdbc/BaseTest.java b/src/test/java/org/mariadb/jdbc/BaseTest.java index 354d8534d..ef0d45479 100644 --- a/src/test/java/org/mariadb/jdbc/BaseTest.java +++ b/src/test/java/org/mariadb/jdbc/BaseTest.java @@ -90,12 +90,12 @@ public class BaseTest { mDefUrl = String.format( "jdbc:mariadb://%s:%s/%s?user=%s&password=%s&%s", - prop.getProperty("DB_HOST"), - prop.getProperty("DB_PORT"), - prop.getProperty("DB_DATABASE"), - prop.getProperty("DB_USER"), - prop.getProperty("DB_PASSWORD"), - prop.getProperty("DB_OTHER")); + System.getProperty("TEST_DB_HOST", prop.getProperty("DB_HOST")), + System.getProperty("TEST_DB_PORT", prop.getProperty("DB_PORT")), + System.getProperty("TEST_DB_DATABASE", prop.getProperty("DB_DATABASE")), + System.getProperty("TEST_DB_USER", prop.getProperty("DB_USER")), + System.getProperty("TEST_DB_PASSWORD", prop.getProperty("DB_PASSWORD")), + System.getProperty("TEST_DB_OTHER", prop.getProperty("DB_OTHER"))); } catch (IOException io) { io.printStackTrace(); From 4ed97b2e458ae4dacf3067fe3705428274f133df Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 11:17:06 +0100 Subject: [PATCH 08/25] [misc] adding benchmark --- .travis.yml | 2 + .travis/script.sh | 15 ++- pom.xml | 95 +++++++++++++++++++ src/benchmark/README.md | 13 +++ .../java/org/mariadb/jdbc/Common.java | 88 +++++++++++++++++ .../java/org/mariadb/jdbc/Select_1.java | 40 ++++++++ .../org/mariadb/jdbc/Select_10000_Rows.java | 46 +++++++++ .../org/mariadb/jdbc/Select_1000_params.java | 64 +++++++++++++ .../java/org/mariadb/jdbc/Select_1_user.java | 44 +++++++++ src/benchmark/resources/logback-test.xml | 33 +++++++ 10 files changed, 436 insertions(+), 4 deletions(-) create mode 100644 src/benchmark/README.md create mode 100644 src/benchmark/java/org/mariadb/jdbc/Common.java create mode 100644 src/benchmark/java/org/mariadb/jdbc/Select_1.java create mode 100644 src/benchmark/java/org/mariadb/jdbc/Select_10000_Rows.java create mode 100644 src/benchmark/java/org/mariadb/jdbc/Select_1000_params.java create mode 100644 src/benchmark/java/org/mariadb/jdbc/Select_1_user.java create mode 100644 src/benchmark/resources/logback-test.xml diff --git a/.travis.yml b/.travis.yml index 88a8a50c7..0a882db60 100644 --- a/.travis.yml +++ b/.travis.yml @@ -55,6 +55,8 @@ matrix: jdk: openjdk11 - env: DB=mariadb:10.5 PACKET=8M jdk: oraclejdk11 + - env: DB=mariadb:10.5 PACKET=8M BENCH=true + jdk: oraclejdk11 - env: DB=mariadb:10.5 PACKET=8M GALERA=true jdk: openjdk11 - env: DB=mariadb:10.5 PACKET=8M PROFILE=true diff --git a/.travis/script.sh b/.travis/script.sh index c74be9f0f..ba50fbc62 100644 --- a/.travis/script.sh +++ b/.travis/script.sh @@ -177,10 +177,17 @@ fi ################################################################################################################### # run test suite ################################################################################################################### -echo "Running coveralls for JDK version: $TRAVIS_JDK_VERSION" -cmd+=( -DdbUrl="$urlString" ) -cmd+=( -DtestSingleHost="$testSingleHost" ) -echo ${cmd} + +if [ -z "$BENCH" ] ; then + echo "Running coveralls for JDK version: $TRAVIS_JDK_VERSION" + cmd+=( -DdbUrl="$urlString" ) + cmd+=( -DtestSingleHost="$testSingleHost" ) + echo ${cmd} +else + echo "Running benchmarks" + mvn clean package -P bench -Dmaven.test.skip + java -Duser.country=US -Duser.language=en -DTEST_PORT=3305 -DTEST_HOST=mariadb.example.com -DTEST_USERNAME=bob -jar target/benchmarks.jar +fi "${cmd[@]}" \ No newline at end of file diff --git a/pom.xml b/pom.xml index c1d37b5a7..7876be95e 100644 --- a/pom.xml +++ b/pom.xml @@ -69,6 +69,7 @@ 5.5.0 6.0.0 5.0.0 + 1.23 @@ -307,4 +308,98 @@ provided + + + + + default + + true + + + + bench + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + mysql + mysql-connector-java + [8.0.20,) + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + src/benchmark/java + + + + + add-resource + generate-resources + + add-resource + + + + + src/benchmark/resources + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.1 + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + + + + + + diff --git a/src/benchmark/README.md b/src/benchmark/README.md new file mode 100644 index 000000000..7bb9ac4e2 --- /dev/null +++ b/src/benchmark/README.md @@ -0,0 +1,13 @@ +

+ + + +

+ +# Benchmark + +How to run : +mvn clean package -P bench -Dmaven.test.skip +java -Duser.country=US -Duser.language=en -jar target/benchmarks.jar + + diff --git a/src/benchmark/java/org/mariadb/jdbc/Common.java b/src/benchmark/java/org/mariadb/jdbc/Common.java new file mode 100644 index 000000000..9b77129a4 --- /dev/null +++ b/src/benchmark/java/org/mariadb/jdbc/Common.java @@ -0,0 +1,88 @@ +/* + * MariaDB Client for Java + * + * Copyright (c) 2012-2014 Monty Program Ab. + * Copyright (c) 2015-2020 MariaDB Corporation Ab. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with this library; if not, write to Monty Program Ab info@montyprogram.com. + * + */ + +package org.mariadb.jdbc; + +import org.openjdk.jmh.annotations.*; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +@State(Scope.Benchmark) +@Warmup(iterations = 10, timeUnit = TimeUnit.SECONDS, time = 1) +@Measurement(iterations = 10, timeUnit = TimeUnit.SECONDS, time = 1) +@Fork(value = 5) +//@Threads(value = 1) // detecting CPU count +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.SECONDS) +public class Common { + + @State(Scope.Thread) + public static class MyState { + + // conf + public final String host = System.getProperty("TEST_HOST", "localhost"); + public final int port = Integer.parseInt(System.getProperty("TEST_PORT", "3306")); + public final String username = System.getProperty("TEST_USERNAME", "root"); + public final String password = System.getProperty("TEST_PASSWORD", ""); + public final String database = System.getProperty("TEST_DATABASE", "testj"); + // connections + protected Connection connection; + @Param({"mysql", "mariadb"}) + String driver; + + @Setup(Level.Trial) + public void doSetup() throws Exception { + String jdbcUrl = + String.format( + "%s:%s/%s?user=%s&password=%s&sslMode=DISABLED&useServerPrepStmts=true", + host, port, database, username, password); + + String className; + switch (driver) { + case "mysql": + className = "com.mysql.cj.jdbc.Driver"; + break; + case "mariadb": + className = "org.mariadb.jdbc.Driver"; + break; + default: + throw new RuntimeException("wrong param"); + } + try { + connection = + ((java.sql.Driver) Class.forName(className).newInstance()) + .connect("jdbc:" + driver + "://" + jdbcUrl, new Properties()); + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + @TearDown(Level.Trial) + public void doTearDown() throws SQLException { + connection.close(); + } + } +} diff --git a/src/benchmark/java/org/mariadb/jdbc/Select_1.java b/src/benchmark/java/org/mariadb/jdbc/Select_1.java new file mode 100644 index 000000000..c3f5918a2 --- /dev/null +++ b/src/benchmark/java/org/mariadb/jdbc/Select_1.java @@ -0,0 +1,40 @@ +/* + * MariaDB Client for Java + * + * Copyright (c) 2012-2014 Monty Program Ab. + * Copyright (c) 2015-2020 MariaDB Corporation Ab. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with this library; if not, write to Monty Program Ab info@montyprogram.com. + * + */ + +package org.mariadb.jdbc; + +import org.openjdk.jmh.annotations.Benchmark; + +import java.sql.ResultSet; +import java.sql.Statement; + +public class Select_1 extends Common { + + @Benchmark + public int run(MyState state) throws Throwable { + try (Statement st = state.connection.createStatement()) { + int rnd = (int) (Math.random() * 1000); + ResultSet rs = st.executeQuery("select " + rnd); + rs.next(); + return rs.getInt(1); + } + } +} diff --git a/src/benchmark/java/org/mariadb/jdbc/Select_10000_Rows.java b/src/benchmark/java/org/mariadb/jdbc/Select_10000_Rows.java new file mode 100644 index 000000000..0e7eadc2e --- /dev/null +++ b/src/benchmark/java/org/mariadb/jdbc/Select_10000_Rows.java @@ -0,0 +1,46 @@ +/* + * MariaDB Client for Java + * + * Copyright (c) 2012-2014 Monty Program Ab. + * Copyright (c) 2015-2020 MariaDB Corporation Ab. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with this library; if not, write to Monty Program Ab info@montyprogram.com. + * + */ + +package org.mariadb.jdbc; + +import org.openjdk.jmh.annotations.Benchmark; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +public class Select_10000_Rows extends Common { + private static final String sql = + "SELECT lpad(conv(floor(rand()*pow(36,8)), 10, 36), 8, 0) as rnd_str_8 FROM seq_1_to_10000"; + + @Benchmark + public String[] run(MyState state) throws Throwable { + try (PreparedStatement st = state.connection.prepareStatement(sql)) { + + ResultSet rs = st.executeQuery(); + String[] res = new String[10000]; + int i = 0; + while (rs.next()) { + res[i++] = rs.getString(1); + } + return res; + } + } +} diff --git a/src/benchmark/java/org/mariadb/jdbc/Select_1000_params.java b/src/benchmark/java/org/mariadb/jdbc/Select_1000_params.java new file mode 100644 index 000000000..bf8afebc4 --- /dev/null +++ b/src/benchmark/java/org/mariadb/jdbc/Select_1000_params.java @@ -0,0 +1,64 @@ +/* + * MariaDB Client for Java + * + * Copyright (c) 2012-2014 Monty Program Ab. + * Copyright (c) 2015-2020 MariaDB Corporation Ab. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with this library; if not, write to Monty Program Ab info@montyprogram.com. + * + */ + +package org.mariadb.jdbc; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.infra.Blackhole; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +public class Select_1000_params extends Common { + + private static final String sql; + + static { + StringBuilder sb = new StringBuilder("select ?"); + for (int i = 1; i < 1000; i++) { + sb.append(",?"); + } + sql = sb.toString(); + } + + private static int[] randParams() { + int[] rnds = new int[1000]; + for (int i = 0; i < 1000; i++) { + rnds[i] = (int) (Math.random() * 1000); + } + return rnds; + } + + @Benchmark + public Integer run(MyState state, Blackhole blackhole) throws Throwable { + int[] rnds = randParams(); + try (PreparedStatement st = state.connection.prepareStatement(sql)) { + for (int i = 1; i <= 1000; i++) { + st.setInt(i, rnds[i - 1]); + } + ResultSet rs = st.executeQuery(); + rs.next(); + Integer val = rs.getInt(1); + if (rnds[0] != val) throw new IllegalStateException("ERROR"); + return val; + } + } +} diff --git a/src/benchmark/java/org/mariadb/jdbc/Select_1_user.java b/src/benchmark/java/org/mariadb/jdbc/Select_1_user.java new file mode 100644 index 000000000..f8bdcb912 --- /dev/null +++ b/src/benchmark/java/org/mariadb/jdbc/Select_1_user.java @@ -0,0 +1,44 @@ +/* + * MariaDB Client for Java + * + * Copyright (c) 2012-2014 Monty Program Ab. + * Copyright (c) 2015-2020 MariaDB Corporation Ab. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with this library; if not, write to Monty Program Ab info@montyprogram.com. + * + */ + +package org.mariadb.jdbc; + +import org.openjdk.jmh.annotations.Benchmark; + +import java.sql.ResultSet; +import java.sql.Statement; + +public class Select_1_user extends Common { + + @Benchmark + public Object[] run(MyState state) throws Throwable { + final int numberOfUserCol = 46; + try (Statement st = state.connection.createStatement()) { + ResultSet rs = st.executeQuery("select * FROM mysql.user LIMIT 1"); + rs.next(); + Object[] objs = new Object[numberOfUserCol]; + for (int i = 0; i < numberOfUserCol; i++) { + objs[i] = rs.getObject(i + 1); + } + return objs; + } + } +} diff --git a/src/benchmark/resources/logback-test.xml b/src/benchmark/resources/logback-test.xml new file mode 100644 index 000000000..1dfb08d9e --- /dev/null +++ b/src/benchmark/resources/logback-test.xml @@ -0,0 +1,33 @@ + + + + + + + + %d{yyyy-MM-dd} | %d{HH:mm:ss.SSS} | %-20.20thread | %5p | %logger{25} | %m%n + + + + + + + + + + + From 8cafdf94d87adee766995e53cdefe55854a451e0 Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 12:17:54 +0100 Subject: [PATCH 09/25] [misc] benchmark correction --- .travis/script.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.travis/script.sh b/.travis/script.sh index ba50fbc62..804ef4fb1 100644 --- a/.travis/script.sh +++ b/.travis/script.sh @@ -183,11 +183,12 @@ if [ -z "$BENCH" ] ; then cmd+=( -DdbUrl="$urlString" ) cmd+=( -DtestSingleHost="$testSingleHost" ) echo ${cmd} + + "${cmd[@]}" + else echo "Running benchmarks" mvn clean package -P bench -Dmaven.test.skip java -Duser.country=US -Duser.language=en -DTEST_PORT=3305 -DTEST_HOST=mariadb.example.com -DTEST_USERNAME=bob -jar target/benchmarks.jar fi - -"${cmd[@]}" \ No newline at end of file From 884e7b9cb3ce89a50a05cbabc6179066c36a8f7e Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 12:20:21 +0100 Subject: [PATCH 10/25] [CONJ-842] Byte array parameters are not send as long data --- .../jdbc/internal/com/send/parameters/ByteArrayParameter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java index 4e4cd6920..2cb83c81a 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java @@ -112,6 +112,6 @@ public boolean isNullData() { } public boolean isLongData() { - return false; + return true; } } From bb602eb786659a067bfcedb796a9f065d9c0d0b5 Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 12:21:01 +0100 Subject: [PATCH 11/25] [misc] test small correction --- src/test/java/org/mariadb/jdbc/BufferTest.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/mariadb/jdbc/BufferTest.java b/src/test/java/org/mariadb/jdbc/BufferTest.java index aedfb274b..a4d2fb5d0 100644 --- a/src/test/java/org/mariadb/jdbc/BufferTest.java +++ b/src/test/java/org/mariadb/jdbc/BufferTest.java @@ -252,10 +252,11 @@ private void sendByteBufferData(boolean compression, char[] arr) throws SQLExcep try (Connection connection = setConnection("&useCompression=" + compression)) { Statement stmt = connection.createStatement(); stmt.execute("TRUNCATE BufferTest"); - PreparedStatement preparedStatement = - connection.prepareStatement("INSERT INTO BufferTest VALUES (?)"); - preparedStatement.setString(1, new String(arr)); - preparedStatement.execute(); + try (PreparedStatement preparedStatement = + connection.prepareStatement("INSERT INTO BufferTest VALUES (?)")) { + preparedStatement.setString(1, new String(arr)); + preparedStatement.execute(); + } checkResult(arr); } } From fd276551dc98549d13f600b721596a6bc43c8d60 Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 12:35:29 +0100 Subject: [PATCH 12/25] [CONJ-841] ResultSetMetaData::getColumnTypeName() returns incorrect type name for LONGTEXT Matadata now return TEXT, MEDIUMTEXT and LONGTEXT datatype --- .../org/mariadb/jdbc/MariaDbResultSetMetaData.java | 2 +- .../java/org/mariadb/jdbc/internal/ColumnType.java | 14 ++++++++++++-- src/test/java/org/mariadb/jdbc/DatatypeTest.java | 8 +++++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java b/src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java index e23449bda..b2d4d56b7 100644 --- a/src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java +++ b/src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java @@ -295,7 +295,7 @@ public int getColumnType(final int column) throws SQLException { public String getColumnTypeName(final int column) throws SQLException { ColumnDefinition ci = getColumnInformation(column); return ColumnType.getColumnTypeName( - ci.getColumnType(), ci.getLength(), ci.isSigned(), ci.isBinary()); + ci.getColumnType(), ci.getLength(), ci.getDisplaySize(), ci.isSigned(), ci.isBinary()); } /** diff --git a/src/main/java/org/mariadb/jdbc/internal/ColumnType.java b/src/main/java/org/mariadb/jdbc/internal/ColumnType.java index 064d101cb..65570d427 100644 --- a/src/main/java/org/mariadb/jdbc/internal/ColumnType.java +++ b/src/main/java/org/mariadb/jdbc/internal/ColumnType.java @@ -225,7 +225,7 @@ public static boolean isNumeric(ColumnType type) { * @return type */ public static String getColumnTypeName( - ColumnType type, long len, boolean signed, boolean binary) { + ColumnType type, long len, long charLen, boolean signed, boolean binary) { switch (type) { case SMALLINT: case MEDIUMINT: @@ -257,7 +257,17 @@ public static String getColumnTypeName( if (binary) { return "VARBINARY"; } - return "VARCHAR"; + if (len < 0) { + return "LONGTEXT"; + } else if (charLen <= 65532) { + return "VARCHAR"; + } else if (charLen <= 65535) { + return "TEXT"; + } else if (charLen <= 16777215) { + return "MEDIUMTEXT"; + } else { + return "LONGTEXT"; + } case STRING: if (binary) { return "BINARY"; diff --git a/src/test/java/org/mariadb/jdbc/DatatypeTest.java b/src/test/java/org/mariadb/jdbc/DatatypeTest.java index a31b4ef37..58efe32cf 100644 --- a/src/test/java/org/mariadb/jdbc/DatatypeTest.java +++ b/src/test/java/org/mariadb/jdbc/DatatypeTest.java @@ -201,6 +201,7 @@ private void createDataTypeTables() throws SQLException { + "tinyblob0 TINYBLOB," + "tinytext0 TINYTEXT," + "blob0 BLOB," + + "bigvarchar VARCHAR(12383)," + "text0 TEXT," + "mediumblob0 MEDIUMBLOB," + "mediumtext0 MEDIUMTEXT," @@ -285,11 +286,12 @@ public void datatypes(Connection connection, boolean tinyInt1isBit, boolean year checkClass("tinyblob0", byteArrayClass, "TINYBLOB", Types.VARBINARY); checkClass("tinytext0", String.class, "VARCHAR", Types.VARCHAR); checkClass("blob0", byteArrayClass, "BLOB", Types.VARBINARY); - checkClass("text0", String.class, "VARCHAR", Types.VARCHAR); + checkClass("bigvarchar", String.class, "VARCHAR", Types.VARCHAR); + checkClass("text0", String.class, "TEXT", Types.VARCHAR); checkClass("mediumblob0", byteArrayClass, "MEDIUMBLOB", Types.VARBINARY); - checkClass("mediumtext0", String.class, "VARCHAR", Types.VARCHAR); + checkClass("mediumtext0", String.class, "MEDIUMTEXT", Types.VARCHAR); checkClass("longblob0", byteArrayClass, "LONGBLOB", Types.LONGVARBINARY); - checkClass("longtext0", String.class, "VARCHAR", Types.LONGVARCHAR); + checkClass("longtext0", String.class, "LONGTEXT", Types.LONGVARCHAR); checkClass("enum0", String.class, "CHAR", Types.CHAR); checkClass("set0", String.class, "CHAR", Types.CHAR); From 0ebe5eabdf9faa9f2bc84f7c307361aa71101491 Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 12:42:24 +0100 Subject: [PATCH 13/25] [CONJ-843] ParameterMetaData::getParameterType for CallableStatement parameter BINARY type now return 'BINARY' --- src/main/java/org/mariadb/jdbc/CallableParameterMetaData.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/mariadb/jdbc/CallableParameterMetaData.java b/src/main/java/org/mariadb/jdbc/CallableParameterMetaData.java index cd1b1a8b4..19e6c66d2 100644 --- a/src/main/java/org/mariadb/jdbc/CallableParameterMetaData.java +++ b/src/main/java/org/mariadb/jdbc/CallableParameterMetaData.java @@ -178,6 +178,8 @@ private int mapMariaDbTypeToJdbc(String str) { return Types.LONGVARBINARY; case "VARBINARY": return Types.VARBINARY; + case "BINARY": + return Types.BINARY; default: return Types.OTHER; } From 256fa8f1425ce1062215b8aad5ff6807c315d883 Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 12:55:31 +0100 Subject: [PATCH 14/25] [misc] added benchmark description --- src/benchmark/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/benchmark/README.md b/src/benchmark/README.md index 7bb9ac4e2..667c3f2e3 100644 --- a/src/benchmark/README.md +++ b/src/benchmark/README.md @@ -7,7 +7,26 @@ # Benchmark How to run : +```script mvn clean package -P bench -Dmaven.test.skip + +# run all benchmarks java -Duser.country=US -Duser.language=en -jar target/benchmarks.jar +# run a specific benchmark +java -Duser.country=US -Duser.language=en -jar target/benchmarks.jar "Select_1_user" +``` + +Configuration by system properties : +* TEST_HOST: localhost +* TEST_PORT: 3306 +* TEST_USERNAME: root +* TEST_PASSWORD: "" +* TEST_DATABASE: "testj" + +example: +```script +mvn clean package -P bench -Dmaven.test.skip +java -DTEST_PORT=3307 -Duser.country=US -Duser.language=en -jar target/benchmarks.jar "Select_1_user" +``` From d633c8dfcf9d62c87cb7de1697f5cb5d322f920b Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 17:39:37 +0100 Subject: [PATCH 15/25] [CONJ-842] Byte array parameters are not send as long data separate long data encoding, permitting sending bulk with long data --- .../mariadb/jdbc/BasePrepareStatement.java | 16 ----------- .../jdbc/ClientSidePreparedStatement.java | 3 +-- .../jdbc/ServerSidePreparedStatement.java | 8 +----- .../org/mariadb/jdbc/internal/ColumnType.java | 1 + .../internal/com/send/ComStmtExecute.java | 2 +- .../send/parameters/BigDecimalParameter.java | 2 +- .../com/send/parameters/BooleanParameter.java | 2 +- .../send/parameters/ByteArrayParameter.java | 6 ++++- .../com/send/parameters/ByteParameter.java | 2 +- .../com/send/parameters/DateParameter.java | 2 +- .../com/send/parameters/DefaultParameter.java | 2 +- .../com/send/parameters/DoubleParameter.java | 2 +- .../com/send/parameters/FloatParameter.java | 2 +- .../com/send/parameters/IntParameter.java | 2 +- .../send/parameters/LocalTimeParameter.java | 2 +- .../com/send/parameters/LongParameter.java | 2 +- .../com/send/parameters/NullParameter.java | 2 +- .../send/parameters/OffsetTimeParameter.java | 2 +- .../com/send/parameters/ParameterHolder.java | 6 ++++- .../com/send/parameters/ReaderParameter.java | 27 ++++++++++++++++++- .../parameters/SerializableParameter.java | 2 +- .../com/send/parameters/ShortParameter.java | 2 +- .../com/send/parameters/StreamParameter.java | 23 +++++++++++++++- .../com/send/parameters/StringParameter.java | 2 +- .../com/send/parameters/TimeParameter.java | 2 +- .../send/parameters/TimestampParameter.java | 2 +- .../parameters/ZonedDateTimeParameter.java | 2 +- .../protocol/AbstractQueryProtocol.java | 24 +++++------------ .../jdbc/internal/protocol/Protocol.java | 6 ++--- src/test/java/org/mariadb/jdbc/BlobTest.java | 4 ++- .../java/org/mariadb/jdbc/BufferTest.java | 14 +++++----- .../java/org/mariadb/jdbc/ConnectionTest.java | 1 - .../org/mariadb/jdbc/ExecuteBatchTest.java | 3 +-- 33 files changed, 100 insertions(+), 80 deletions(-) diff --git a/src/main/java/org/mariadb/jdbc/BasePrepareStatement.java b/src/main/java/org/mariadb/jdbc/BasePrepareStatement.java index 9efa0550c..688f4d71f 100644 --- a/src/main/java/org/mariadb/jdbc/BasePrepareStatement.java +++ b/src/main/java/org/mariadb/jdbc/BasePrepareStatement.java @@ -96,7 +96,6 @@ public abstract class BasePrepareStatement extends MariaDbStatement implements P .toFormatter(); protected int autoGeneratedKeys; - protected boolean hasLongData = false; private boolean useFractionalSeconds; private boolean noBackslashEscapes; @@ -173,7 +172,6 @@ public void setCharacterStream(final int parameterIndex, final Reader reader, fi return; } setParameter(parameterIndex, new ReaderParameter(reader, length, noBackslashEscapes)); - hasLongData = true; } /** @@ -200,7 +198,6 @@ public void setCharacterStream(final int parameterIndex, final Reader reader, fi return; } setParameter(parameterIndex, new ReaderParameter(reader, length, noBackslashEscapes)); - hasLongData = true; } /** @@ -229,7 +226,6 @@ public void setCharacterStream(final int parameterIndex, final Reader reader) return; } setParameter(parameterIndex, new ReaderParameter(reader, noBackslashEscapes)); - hasLongData = true; } /** @@ -264,7 +260,6 @@ public void setBlob(final int parameterIndex, final Blob blob) throws SQLExcepti setParameter( parameterIndex, new StreamParameter(blob.getBinaryStream(), blob.length(), noBackslashEscapes)); - hasLongData = true; } /** @@ -292,7 +287,6 @@ public void setBlob(final int parameterIndex, final InputStream inputStream, fin return; } setParameter(parameterIndex, new StreamParameter(inputStream, length, noBackslashEscapes)); - hasLongData = true; } /** @@ -320,7 +314,6 @@ public void setBlob(final int parameterIndex, final InputStream inputStream) thr } setParameter(parameterIndex, new StreamParameter(inputStream, noBackslashEscapes)); - hasLongData = true; } /** @@ -342,7 +335,6 @@ public void setClob(final int parameterIndex, final Clob clob) throws SQLExcepti setParameter( parameterIndex, new ReaderParameter(clob.getCharacterStream(), clob.length(), noBackslashEscapes)); - hasLongData = true; } /** @@ -929,7 +921,6 @@ public void setObject(final int parameterIndex, final Object obj) throws SQLExce } else { // fallback to sending serialized object setParameter(parameterIndex, new SerializableParameter(obj, noBackslashEscapes)); - hasLongData = true; } } @@ -1177,7 +1168,6 @@ public void setAsciiStream(final int parameterIndex, final InputStream stream, f return; } setParameter(parameterIndex, new StreamParameter(stream, length, noBackslashEscapes)); - hasLongData = true; } /** @@ -1209,7 +1199,6 @@ public void setAsciiStream(final int parameterIndex, final InputStream stream) return; } setParameter(parameterIndex, new StreamParameter(stream, noBackslashEscapes)); - hasLongData = true; } /** @@ -1236,7 +1225,6 @@ public void setAsciiStream(final int parameterIndex, final InputStream stream, f return; } setParameter(parameterIndex, new StreamParameter(stream, length, noBackslashEscapes)); - hasLongData = true; } /** @@ -1262,7 +1250,6 @@ public void setBinaryStream(final int parameterIndex, final InputStream stream, return; } setParameter(parameterIndex, new StreamParameter(stream, length, noBackslashEscapes)); - hasLongData = true; } /** @@ -1292,7 +1279,6 @@ public void setBinaryStream(final int parameterIndex, final InputStream stream) return; } setParameter(parameterIndex, new StreamParameter(stream, noBackslashEscapes)); - hasLongData = true; } /** @@ -1318,7 +1304,6 @@ public void setBinaryStream(final int parameterIndex, final InputStream stream, return; } setParameter(parameterIndex, new StreamParameter(stream, length, noBackslashEscapes)); - hasLongData = true; } /** @@ -1430,7 +1415,6 @@ public void setUnicodeStream(final int parameterIndex, final InputStream x, fina return; } setParameter(parameterIndex, new StreamParameter(x, length, noBackslashEscapes)); - hasLongData = true; } public void setInt(final int column, final int value) throws SQLException { diff --git a/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java index d4863ca64..233a1b809 100644 --- a/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java +++ b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java @@ -279,7 +279,6 @@ public void addBatch(final String sql) throws SQLException { @Override public void clearBatch() { parameterList.clear(); - hasLongData = false; this.parameters = new ParameterHolder[prepareResult.getParamCount()]; } @@ -368,7 +367,7 @@ private void executeInternalBatch(int size) throws SQLException { null, null); if (protocol.executeBatchClient( - protocol.isMasterConnection(), results, prepareResult, parameterList, hasLongData)) { + protocol.isMasterConnection(), results, prepareResult, parameterList)) { return; } diff --git a/src/main/java/org/mariadb/jdbc/ServerSidePreparedStatement.java b/src/main/java/org/mariadb/jdbc/ServerSidePreparedStatement.java index d3dbae7fc..af4cdae34 100644 --- a/src/main/java/org/mariadb/jdbc/ServerSidePreparedStatement.java +++ b/src/main/java/org/mariadb/jdbc/ServerSidePreparedStatement.java @@ -148,7 +148,6 @@ public void addBatch(final String sql) throws SQLException { public void clearBatch() { queryParameters.clear(); - hasLongData = false; } @Override @@ -255,12 +254,7 @@ private void executeBatchInternal(int queryParameterSize) throws SQLException { // if multi send capacity if ((options.useBatchMultiSend || options.useBulkStmts) && (protocol.executeBatchServer( - mustExecuteOnMaster, - serverPrepareResult, - results, - sql, - queryParameters, - hasLongData))) { + mustExecuteOnMaster, serverPrepareResult, results, sql, queryParameters))) { if (metadata == null) { setMetaFromResult(); // first prepare } diff --git a/src/main/java/org/mariadb/jdbc/internal/ColumnType.java b/src/main/java/org/mariadb/jdbc/internal/ColumnType.java index 65570d427..f63ededa9 100644 --- a/src/main/java/org/mariadb/jdbc/internal/ColumnType.java +++ b/src/main/java/org/mariadb/jdbc/internal/ColumnType.java @@ -220,6 +220,7 @@ public static boolean isNumeric(ColumnType type) { * * @param type type * @param len len + * @param charLen character length * @param signed signed * @param binary binary * @return type diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtExecute.java b/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtExecute.java index 2e8d754cd..500467adf 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtExecute.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtExecute.java @@ -131,7 +131,7 @@ public static void writeCmd( for (int i = 0; i < parameterCount; i++) { ParameterHolder holder = parameters[i]; - if (!holder.isNullData() && !holder.isLongData()) { + if (!holder.isNullData() && !holder.canBeLongData()) { holder.writeBinary(pos); } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BigDecimalParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BigDecimalParameter.java index 0a63f24ea..606476c3c 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BigDecimalParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BigDecimalParameter.java @@ -98,7 +98,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BooleanParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BooleanParameter.java index 445722329..602b77a7f 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BooleanParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/BooleanParameter.java @@ -65,7 +65,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java index 2cb83c81a..b7d97ecdb 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteArrayParameter.java @@ -94,6 +94,10 @@ public void writeBinary(final PacketOutputStream pos) throws IOException { pos.write(bytes); } + public void writeLongData(final PacketOutputStream pos) throws IOException { + pos.write(bytes); + } + public ColumnType getColumnType() { return ColumnType.VARSTRING; } @@ -111,7 +115,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return true; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteParameter.java index 5d031b085..ee8713309 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ByteParameter.java @@ -102,7 +102,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DateParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DateParameter.java index 4dca208dd..657e9ba12 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DateParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DateParameter.java @@ -132,7 +132,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DefaultParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DefaultParameter.java index 4b1ef8f59..3d772ca90 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DefaultParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DefaultParameter.java @@ -97,7 +97,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DoubleParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DoubleParameter.java index 7a9a24b95..7fea18314 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DoubleParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DoubleParameter.java @@ -95,7 +95,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/FloatParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/FloatParameter.java index ae1c54000..28e3dc6f1 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/FloatParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/FloatParameter.java @@ -95,7 +95,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/IntParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/IntParameter.java index 9be8a9834..4b5ea14a1 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/IntParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/IntParameter.java @@ -95,7 +95,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LocalTimeParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LocalTimeParameter.java index 3f821d384..0c39794e2 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LocalTimeParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LocalTimeParameter.java @@ -116,7 +116,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LongParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LongParameter.java index 5b3f9e0b2..573a60bb2 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LongParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/LongParameter.java @@ -94,7 +94,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/NullParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/NullParameter.java index 3e3d42fbc..305d8bee5 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/NullParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/NullParameter.java @@ -99,7 +99,7 @@ public boolean isNullData() { return true; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/OffsetTimeParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/OffsetTimeParameter.java index 73a61eebe..ee18abc90 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/OffsetTimeParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/OffsetTimeParameter.java @@ -148,7 +148,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ParameterHolder.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ParameterHolder.java index 2142c2dea..80239ac75 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ParameterHolder.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ParameterHolder.java @@ -71,6 +71,10 @@ public interface ParameterHolder { void writeBinary(PacketOutputStream pos) throws IOException; + default void writeLongData(PacketOutputStream pos) throws IOException { + return; + } + int getApproximateTextProtocolLength() throws IOException; String toString(); @@ -79,5 +83,5 @@ public interface ParameterHolder { ColumnType getColumnType(); - boolean isLongData(); + boolean canBeLongData(); } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ReaderParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ReaderParameter.java index aeb852815..0459c1837 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ReaderParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ReaderParameter.java @@ -52,8 +52,10 @@ package org.mariadb.jdbc.internal.com.send.parameters; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Reader; +import java.nio.charset.StandardCharsets; import org.mariadb.jdbc.internal.ColumnType; import org.mariadb.jdbc.internal.io.output.PacketOutputStream; @@ -112,6 +114,29 @@ public int getApproximateTextProtocolLength() { * @throws IOException if socket error occur */ public void writeBinary(final PacketOutputStream pos) throws IOException { + ByteArrayOutputStream bb = new ByteArrayOutputStream(); + char[] buf = new char[4096]; + int len; + if (length == Long.MAX_VALUE) { + while ((len = reader.read(buf)) >= 0) { + byte[] data = new String(buf, 0, len).getBytes(StandardCharsets.UTF_8); + bb.write(data, 0, data.length); + } + } else { + long maxLen = length; + while ((len = reader.read(buf)) >= 0 && maxLen > 0) { + byte[] data = + new String(buf, 0, Math.min(len, (int) maxLen)).getBytes(StandardCharsets.UTF_8); + maxLen -= len; + bb.write(data, 0, data.length); + } + } + byte[] val = bb.toByteArray(); + pos.writeFieldLength(val.length); + pos.write(val); + } + + public void writeLongData(final PacketOutputStream pos) throws IOException { if (length == Long.MAX_VALUE) { pos.write(reader, false, noBackslashEscapes); } else { @@ -132,7 +157,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return true; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/SerializableParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/SerializableParameter.java index 5ea11def0..e2abcf449 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/SerializableParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/SerializableParameter.java @@ -130,7 +130,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ShortParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ShortParameter.java index bd627cd55..68a982123 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ShortParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ShortParameter.java @@ -95,7 +95,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StreamParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StreamParameter.java index 6b122494d..ff4249c7f 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StreamParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StreamParameter.java @@ -52,6 +52,7 @@ package org.mariadb.jdbc.internal.com.send.parameters; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.mariadb.jdbc.internal.ColumnType; @@ -112,6 +113,26 @@ public int getApproximateTextProtocolLength() { * @throws IOException if socket error occur */ public void writeBinary(final PacketOutputStream pos) throws IOException { + ByteArrayOutputStream bb = new ByteArrayOutputStream(); + byte[] array = new byte[4096]; + int len; + if (length == Long.MAX_VALUE) { + while ((len = is.read(array)) > 0) { + bb.write(array, 0, len); + } + } else { + long maxLen = length; + while ((len = is.read(array)) > 0 && maxLen > 0) { + bb.write(array, 0, Math.min(len, (int) maxLen)); + maxLen -= len; + } + } + byte[] val = bb.toByteArray(); + pos.writeFieldLength(val.length); + pos.write(val); + } + + public void writeLongData(final PacketOutputStream pos) throws IOException { if (length == Long.MAX_VALUE) { pos.write(is, false, noBackslashEscapes); } else { @@ -132,7 +153,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return true; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StringParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StringParameter.java index d0ba73a6d..8eccfe262 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StringParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/StringParameter.java @@ -109,7 +109,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimeParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimeParameter.java index 6c7d5bdc8..df3d147a4 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimeParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimeParameter.java @@ -150,7 +150,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimestampParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimestampParameter.java index 8c10218b4..6b8a1018a 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimestampParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimestampParameter.java @@ -147,7 +147,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ZonedDateTimeParameter.java b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ZonedDateTimeParameter.java index 3617a2d78..e5b95ea8f 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ZonedDateTimeParameter.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ZonedDateTimeParameter.java @@ -138,7 +138,7 @@ public boolean isNullData() { return false; } - public boolean isLongData() { + public boolean canBeLongData() { return false; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java index 5440264cc..f7f0c4735 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java @@ -372,15 +372,13 @@ public void executeQuery( * @param results results * @param prepareResult ClientPrepareResult * @param parametersList List of parameters - * @param hasLongData has parameter with long data (stream) * @throws SQLException exception */ public boolean executeBatchClient( boolean mustExecuteOnMaster, Results results, final ClientPrepareResult prepareResult, - final List parametersList, - boolean hasLongData) + final List parametersList) throws SQLException { // *********************************************************************************************************** @@ -404,7 +402,6 @@ public boolean executeBatchClient( } else if (prepareResult.isQueryMultipleRewritable()) { if (options.useBulkStmts - && !hasLongData && prepareResult.isQueryMultipleRewritable() // INSERT FROM SELECT not allowed && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS && executeBulkBatch(results, prepareResult.getSql(), null, parametersList)) { @@ -419,7 +416,6 @@ && executeBulkBatch(results, prepareResult.getSql(), null, parametersList)) { } if (options.useBulkStmts - && !hasLongData && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS && executeBulkBatch(results, prepareResult.getSql(), null, parametersList)) { return true; @@ -454,22 +450,19 @@ private boolean executeBulkBatch( // ************************************************************************************** // Ensure BULK can be use : // - server support bulk - // - no stream // - parameter type doesn't change // - avoid INSERT FROM SELECT // ************************************************************************************** if ((serverCapabilities & MariaDbServerCapabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS) == 0) return false; - // ensure that there is no long data and type doesn't change + // ensure that type doesn't change ParameterHolder[] initParameters = parametersList.get(0); int parameterCount = initParameters.length; short[] types = new short[parameterCount]; for (int i = 0; i < parameterCount; i++) { types[i] = initParameters[i].getColumnType().getType(); } - - // must ensure that data type doesn't change for (ParameterHolder[] parameters : parametersList) { for (int i = 0; i < parameterCount; i++) { if (parameters[i].getColumnType().getType() != types[i]) { @@ -991,7 +984,6 @@ private void executeBatchRewrite( * @param results execution results * @param sql sql query if needed to be prepared * @param parametersList parameter list - * @param hasLongData has long data (stream) * @return executed * @throws SQLException if parameter error or connection error occur. */ @@ -1000,14 +992,12 @@ public boolean executeBatchServer( ServerPrepareResult serverPrepareResult, Results results, String sql, - final List parametersList, - boolean hasLongData) + final List parametersList) throws SQLException { cmdPrologue(); if (options.useBulkStmts - && !hasLongData && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS && executeBulkBatch(results, sql, serverPrepareResult, parametersList)) { return true; @@ -1040,12 +1030,12 @@ public void sendCmd( // send binary data in a separate stream for (int i = 0; i < paramCount; i++) { - if (parameters[i].isLongData()) { + if (parameters[i].canBeLongData()) { writer.startPacket(0); writer.write(COM_STMT_SEND_LONG_DATA); writer.writeInt(statementId); writer.writeShort((short) i); - parameters[i].writeBinary(writer); + parameters[i].writeLongData(writer); writer.flush(); } } @@ -1114,12 +1104,12 @@ public void executePreparedQuery( // send binary data in a separate stream for (int i = 0; i < parameterCount; i++) { - if (parameters[i].isLongData()) { + if (parameters[i].canBeLongData()) { writer.startPacket(0); writer.write(COM_STMT_SEND_LONG_DATA); writer.writeInt(serverPrepareResult.getStatementId()); writer.writeShort((short) i); - parameters[i].writeBinary(writer); + parameters[i].writeLongData(writer); writer.flush(); } } diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java index 99fcfa6b8..f3ea6ac9e 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java @@ -172,8 +172,7 @@ boolean executeBatchClient( boolean mustExecuteOnMaster, Results results, final ClientPrepareResult prepareResult, - final List parametersList, - boolean hasLongData) + final List parametersList) throws SQLException; void executeBatchStmt(boolean mustExecuteOnMaster, Results results, final List queries) @@ -191,8 +190,7 @@ boolean executeBatchServer( ServerPrepareResult serverPrepareResult, Results results, String sql, - List parameterList, - boolean hasLongData) + List parameterList) throws SQLException; void getResult(Results results) throws SQLException; diff --git a/src/test/java/org/mariadb/jdbc/BlobTest.java b/src/test/java/org/mariadb/jdbc/BlobTest.java index fe7fcbacb..bf68b18cd 100644 --- a/src/test/java/org/mariadb/jdbc/BlobTest.java +++ b/src/test/java/org/mariadb/jdbc/BlobTest.java @@ -444,7 +444,9 @@ public void conj77() throws Exception { bout.write(buffer, 0, read); } } - assertArrayEquals(bout.toByteArray(), values[pos++]); + byte[] expected = values[pos++]; + assertEquals(expected.length, bout.toByteArray().length); + assertArrayEquals(expected, bout.toByteArray()); } } else { assertNull(values[pos++]); diff --git a/src/test/java/org/mariadb/jdbc/BufferTest.java b/src/test/java/org/mariadb/jdbc/BufferTest.java index a4d2fb5d0..d6b2e40a9 100644 --- a/src/test/java/org/mariadb/jdbc/BufferTest.java +++ b/src/test/java/org/mariadb/jdbc/BufferTest.java @@ -82,7 +82,7 @@ public class BufferTest extends BaseTest { @BeforeClass() public static void initClass() throws SQLException { - createTable("BufferTest", "test longText"); + createTable("buffer_test", "test longText"); } @Test @@ -205,7 +205,7 @@ public void send20mByteBufferCompressDataException() { assertTrue( sqlexception .getMessage() - .contains("INSERT INTO BufferTest VALUES (?), parameters ['" + array20m[0])); + .contains("INSERT INTO buffer_test VALUES (?), parameters ['" + array20m[0])); } assertTrue( "not the expected exception. was " + sqlexception.getCause().getCause().getMessage(), @@ -251,9 +251,9 @@ public void send40mByteBufferCompressDataException() { private void sendByteBufferData(boolean compression, char[] arr) throws SQLException { try (Connection connection = setConnection("&useCompression=" + compression)) { Statement stmt = connection.createStatement(); - stmt.execute("TRUNCATE BufferTest"); + stmt.execute("TRUNCATE buffer_test"); try (PreparedStatement preparedStatement = - connection.prepareStatement("INSERT INTO BufferTest VALUES (?)")) { + connection.prepareStatement("INSERT INTO buffer_test VALUES (?)")) { preparedStatement.setString(1, new String(arr)); preparedStatement.execute(); } @@ -271,15 +271,15 @@ private void sendByteBufferData(boolean compression, char[] arr) throws SQLExcep private void sendSqlData(boolean compression, char[] arr) throws SQLException { try (Connection connection = setConnection("&useCompression=" + compression)) { Statement stmt = connection.createStatement(); - stmt.execute("TRUNCATE BufferTest"); - stmt.execute("INSERT INTO BufferTest VALUES ('" + new String(arr) + "')"); + stmt.execute("TRUNCATE buffer_test"); + stmt.execute("INSERT INTO buffer_test VALUES ('" + new String(arr) + "')"); checkResult(arr); } } private void checkResult(char[] arr) throws SQLException { Statement stmt = sharedConnection.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM BufferTest"); + ResultSet rs = stmt.executeQuery("SELECT * FROM buffer_test"); if (rs.next()) { String resString = rs.getString(1); char[] cc = resString.toCharArray(); diff --git a/src/test/java/org/mariadb/jdbc/ConnectionTest.java b/src/test/java/org/mariadb/jdbc/ConnectionTest.java index 9af8ffdc3..140f2e005 100644 --- a/src/test/java/org/mariadb/jdbc/ConnectionTest.java +++ b/src/test/java/org/mariadb/jdbc/ConnectionTest.java @@ -670,7 +670,6 @@ private void checkConnection(String conUrl, int min, int max) { // excepted exception // since retriesAllDown is = 20 , that means 10 entire loop with 250ms sleep // first loop has not sleep, last too, so 8 * 250 = 2s - System.out.println(System.currentTimeMillis() - start); assertTrue(System.currentTimeMillis() - start > min); assertTrue(System.currentTimeMillis() - start < max); } diff --git a/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java b/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java index 4300a4358..3664cc5a7 100644 --- a/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java +++ b/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java @@ -356,14 +356,13 @@ public void useBatchMultiSend() throws Exception { @Test public void ensureBulkSchedulerMaxPoolSizeRejection() throws Throwable { Assume.assumeFalse(sharedIsAurora() || sharedOptions().profileSql); - System.out.println(getProtocolFromConnection(sharedConnection).getHostAddress()); Statement statement = sharedConnection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT @@max_connections"); assertTrue(resultSet.next()); int maxConnection = resultSet.getInt(1); int limit = Math.min(1, Math.min(200, maxConnection - 10)); - System.out.println("limit:" + limit); + for (int i = 0; i < limit; i++) { createTable("multipleSimultaneousBatch_" + i, "a INT NOT NULL"); } From cb926cdcdc658bb4831baad182127cffcabd6128 Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 16 Nov 2020 18:17:09 +0100 Subject: [PATCH 16/25] [misc] enable load local infile test for MariaDB 10.4+ --- .../jdbc/LocalInfileInputStreamTest.java | 28 +++++++------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java b/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java index 5b9d4cce0..865f32377 100644 --- a/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java +++ b/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java @@ -80,12 +80,11 @@ public static void initClass() throws SQLException { @Test public void testLocalInfileInputStream() throws SQLException { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); try (Connection connection = setConnection("&allowLocalInfile=true")) { try (Statement st = connection.createStatement()) { // Build a tab-separated record file - String builder = "1\thello\n" + "2\tworld\n"; + String builder = "1\thello\n2\tworld\n"; InputStream inputStream = new ByteArrayInputStream(builder.getBytes()); ((MariaDbStatement) st).setLocalInfileInputStream(inputStream); @@ -108,8 +107,7 @@ public void testLocalInfileInputStream() throws SQLException { @Test public void testLocalInfileValidInterceptor() throws Exception { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); File temp = File.createTempFile("validateInfile", ".txt"); StringBuilder builder = new StringBuilder(); builder.append("1,hello\n"); @@ -124,8 +122,7 @@ public void testLocalInfileValidInterceptor() throws Exception { @Test public void testLocalInfileUnValidInterceptor() throws Exception { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); File temp = File.createTempFile("localInfile", ".txt"); StringBuilder builder = new StringBuilder(); builder.append("1,hello\n"); @@ -175,8 +172,7 @@ private void testLocalInfile(Connection connection, String file) throws SQLExcep @SuppressWarnings("ResultOfMethodCallIgnored") @Test public void loadDataInfileEmpty() throws SQLException, IOException { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); // Create temp file. File temp = File.createTempFile("validateInfile", ".tmp"); try (Connection connection = setConnection("&allowLocalInfile=true")) { @@ -195,13 +191,12 @@ public void loadDataInfileEmpty() throws SQLException, IOException { @Test public void testPrepareLocalInfileWithoutInputStream() throws SQLException { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); try (Connection connection = setConnection("&allowLocalInfile=true")) { try { PreparedStatement st = connection.prepareStatement( - "LOAD DATA LOCAL INFILE 'validateInfile.tsv' " + "INTO TABLE ldinfile"); + "LOAD DATA LOCAL INFILE 'validateInfile.tsv' INTO TABLE ldinfile"); st.execute(); fail(); } catch (SQLException e) { @@ -282,23 +277,20 @@ private void checkBigLocalInfile(long fileSize) throws Exception { */ @Test public void testSmallBigLocalInfileInputStream() throws Exception { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); checkBigLocalInfile(256); } @Test public void test2xBigLocalInfileInputStream() throws Exception { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); Assume.assumeTrue(checkMaxAllowedPacketMore40m("test2xBigLocalInfileInputStream")); checkBigLocalInfile(16777216 * 2); } @Test public void testMoreThanMaxAllowedPacketLocalInfileInputStream() throws Exception { - Assume.assumeFalse( - (isMariadbServer() && minVersion(10, 4, 0)) || (!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); Assume.assumeTrue(System.getenv("SKYSQL") == null); Assume.assumeFalse(sharedIsAurora()); Statement stmt = sharedConnection.createStatement(); From 37fde5fc1c34b00bbb32a8e7a20a41f09ef7fc9a Mon Sep 17 00:00:00 2001 From: rusher Date: Tue, 17 Nov 2020 10:05:09 +0100 Subject: [PATCH 17/25] [misc] test correction for maxscale and SkySQL environment --- src/test/java/org/mariadb/jdbc/FetchSizeTest.java | 1 + .../java/org/mariadb/jdbc/LocalInfileInputStreamTest.java | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/src/test/java/org/mariadb/jdbc/FetchSizeTest.java b/src/test/java/org/mariadb/jdbc/FetchSizeTest.java index 6f9020d50..fba83fbf5 100644 --- a/src/test/java/org/mariadb/jdbc/FetchSizeTest.java +++ b/src/test/java/org/mariadb/jdbc/FetchSizeTest.java @@ -201,6 +201,7 @@ private void prepareRecords(int recordNumber, String tableName) throws SQLExcept */ @Test public void fetchSizeCancel() throws SQLException { + Assume.assumeTrue(System.getenv("MAXSCALE_TEST_DISABLE") == null); Assume.assumeTrue(minVersion(10, 1)); // 10.1.2 in fact Assume.assumeTrue(!sharedOptions().profileSql); long start = System.currentTimeMillis(); diff --git a/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java b/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java index 865f32377..3705ac122 100644 --- a/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java +++ b/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java @@ -81,6 +81,7 @@ public static void initClass() throws SQLException { @Test public void testLocalInfileInputStream() throws SQLException { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeTrue(System.getenv("SKYSQL") == null); try (Connection connection = setConnection("&allowLocalInfile=true")) { try (Statement st = connection.createStatement()) { // Build a tab-separated record file @@ -108,6 +109,7 @@ public void testLocalInfileInputStream() throws SQLException { @Test public void testLocalInfileValidInterceptor() throws Exception { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeTrue(System.getenv("SKYSQL") == null); File temp = File.createTempFile("validateInfile", ".txt"); StringBuilder builder = new StringBuilder(); builder.append("1,hello\n"); @@ -123,6 +125,7 @@ public void testLocalInfileValidInterceptor() throws Exception { @Test public void testLocalInfileUnValidInterceptor() throws Exception { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeTrue(System.getenv("SKYSQL") == null); File temp = File.createTempFile("localInfile", ".txt"); StringBuilder builder = new StringBuilder(); builder.append("1,hello\n"); @@ -173,6 +176,7 @@ private void testLocalInfile(Connection connection, String file) throws SQLExcep @Test public void loadDataInfileEmpty() throws SQLException, IOException { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeTrue(System.getenv("SKYSQL") == null); // Create temp file. File temp = File.createTempFile("validateInfile", ".tmp"); try (Connection connection = setConnection("&allowLocalInfile=true")) { @@ -192,6 +196,7 @@ public void loadDataInfileEmpty() throws SQLException, IOException { @Test public void testPrepareLocalInfileWithoutInputStream() throws SQLException { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeTrue(System.getenv("SKYSQL") == null); try (Connection connection = setConnection("&allowLocalInfile=true")) { try { PreparedStatement st = @@ -278,11 +283,13 @@ private void checkBigLocalInfile(long fileSize) throws Exception { @Test public void testSmallBigLocalInfileInputStream() throws Exception { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); + Assume.assumeTrue(System.getenv("SKYSQL") == null); checkBigLocalInfile(256); } @Test public void test2xBigLocalInfileInputStream() throws Exception { + Assume.assumeTrue(System.getenv("SKYSQL") == null); Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); Assume.assumeTrue(checkMaxAllowedPacketMore40m("test2xBigLocalInfileInputStream")); checkBigLocalInfile(16777216 * 2); From 29df5f5a312c1f56380759b5b83689111bc1b4c5 Mon Sep 17 00:00:00 2001 From: rusher Date: Tue, 17 Nov 2020 12:12:31 +0100 Subject: [PATCH 18/25] [misc] ensure test before will be executed before test class --- src/test/java/org/mariadb/jdbc/BaseTest.java | 6 +++--- src/test/java/org/mariadb/jdbc/CredentialPluginTest.java | 4 ++-- .../org/mariadb/jdbc/ResultSetUnsupportedMethodsTest.java | 2 +- src/test/java/org/mariadb/jdbc/TransactionTest.java | 4 ++-- .../java/org/mariadb/jdbc/UpdateResultSetMethodsTest.java | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/test/java/org/mariadb/jdbc/BaseTest.java b/src/test/java/org/mariadb/jdbc/BaseTest.java index ef0d45479..20456aedb 100644 --- a/src/test/java/org/mariadb/jdbc/BaseTest.java +++ b/src/test/java/org/mariadb/jdbc/BaseTest.java @@ -150,7 +150,7 @@ protected void finished(Description description) { } catch (SQLNonTransientConnectionException connFail) { connFail.printStackTrace(); try { - beforeClassBaseTest(); + before(); } catch (SQLException e) { System.out.println("ERROR reconnecting"); e.printStackTrace(); @@ -205,7 +205,7 @@ protected void failed(Throwable throwable, Description description) { * @throws SQLException exception */ @BeforeClass() - public static void beforeClassBaseTest() throws SQLException { + public static void before() throws SQLException { String url = System.getProperty("dbUrl", mDefUrl); runLongTest = Boolean.parseBoolean(System.getProperty("runLongTest", "false")); testSingleHost = Boolean.parseBoolean(System.getProperty("testSingleHost", "true")); @@ -287,7 +287,7 @@ private static void setUri() { * @throws SQLException exception */ @AfterClass - public static void afterClassBaseTest() throws SQLException { + public static void after() throws SQLException { if (testSingleHost && sharedConnection != null && !sharedConnection.isClosed()) { if (!tempViewList.isEmpty()) { Statement stmt = sharedConnection.createStatement(); diff --git a/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java b/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java index 889de3c3b..337c95fc1 100644 --- a/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java +++ b/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java @@ -35,7 +35,7 @@ public class CredentialPluginTest extends BaseTest { * @throws SQLException if any */ @Before - public void before() throws SQLException { + public void beforeTest() throws SQLException { boolean useOldNotation = true; if ((isMariadbServer() && minVersion(10, 2, 0)) || (!isMariadbServer() && minVersion(8, 0, 0))) { @@ -68,7 +68,7 @@ public void before() throws SQLException { * @throws SQLException if any */ @After - public void after() throws SQLException { + public void afterTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("DROP USER IF EXISTS 'identityUser'@'%'"); stmt.execute("DROP USER IF EXISTS 'identityUser'@'localhost'"); diff --git a/src/test/java/org/mariadb/jdbc/ResultSetUnsupportedMethodsTest.java b/src/test/java/org/mariadb/jdbc/ResultSetUnsupportedMethodsTest.java index 9e3a9e745..4b76a665a 100644 --- a/src/test/java/org/mariadb/jdbc/ResultSetUnsupportedMethodsTest.java +++ b/src/test/java/org/mariadb/jdbc/ResultSetUnsupportedMethodsTest.java @@ -63,7 +63,7 @@ public class ResultSetUnsupportedMethodsTest extends BaseTest { private ResultSet rs; @Before - public void before() throws SQLException { + public void beforeTest() throws SQLException { rs = sharedConnection.createStatement().executeQuery("select 1"); } diff --git a/src/test/java/org/mariadb/jdbc/TransactionTest.java b/src/test/java/org/mariadb/jdbc/TransactionTest.java index 4c2258d85..878498f4c 100644 --- a/src/test/java/org/mariadb/jdbc/TransactionTest.java +++ b/src/test/java/org/mariadb/jdbc/TransactionTest.java @@ -70,7 +70,7 @@ public class TransactionTest extends BaseTest { * @throws SQLException exception */ @Before - public void before() throws SQLException { + public void beforeTest() throws SQLException { if (testSingleHost) { Statement stmt = sharedConnection.createStatement(); stmt.execute("drop table if exists tx_fore_key"); @@ -90,7 +90,7 @@ public void before() throws SQLException { * @throws SQLException exception */ @After - public void after() throws SQLException { + public void afterTest() throws SQLException { if (testSingleHost) { Statement stmt = sharedConnection.createStatement(); stmt.execute("drop table if exists tx_fore_key"); diff --git a/src/test/java/org/mariadb/jdbc/UpdateResultSetMethodsTest.java b/src/test/java/org/mariadb/jdbc/UpdateResultSetMethodsTest.java index 0bb7e0c0d..5ec0a6ac7 100644 --- a/src/test/java/org/mariadb/jdbc/UpdateResultSetMethodsTest.java +++ b/src/test/java/org/mariadb/jdbc/UpdateResultSetMethodsTest.java @@ -69,7 +69,7 @@ public class UpdateResultSetMethodsTest extends BaseTest { * @throws SQLException exception */ @Before - public void before() throws SQLException { + public void beforeTest() throws SQLException { rs = sharedConnection .createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE) From 2af5b1a273374508aac10aa30bcc4505c6ad54ef Mon Sep 17 00:00:00 2001 From: rusher Date: Tue, 17 Nov 2020 15:03:03 +0100 Subject: [PATCH 19/25] [CONJ-839] batch exception message correction when with option `rewriteBatchedStatements` batch message was resulting in Error reading results in place of error. --- .../protocol/AbstractQueryProtocol.java | 20 ++++++++--- .../ClientPreparedStatementParsingTest.java | 35 +++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java index f7f0c4735..4b1c007cc 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java @@ -671,10 +671,22 @@ public SQLException handleResultException( int counter = results.getCurrentStatNumber() - 1; ParameterHolder[] parameters = parametersList.get(counter); List queryParts = clientPrepareResult.getQueryParts(); - StringBuilder sql = new StringBuilder(new String(queryParts.get(0))); - for (int i = 0; i < paramCount; i++) { - sql.append(parameters[i].toString()).append(new String(queryParts.get(i + 1))); + StringBuilder sql; + if (clientPrepareResult.isRewriteType()) { + // build sql from rewrite parsing + sql = new StringBuilder(new String(queryParts.get(0))); + sql.append(new String(queryParts.get(1))); + for (int i = 0; i < paramCount; i++) { + sql.append(parameters[i].toString()).append(new String(queryParts.get(i + 2))); + } + sql.append(new String(queryParts.get(paramCount + 2))); + } else { + // build sql from basic parsing + sql = new StringBuilder(new String(queryParts.get(0))); + for (int i = 0; i < paramCount; i++) { + sql.append(parameters[i].toString()).append(new String(queryParts.get(i + 1))); + } } return exceptionWithQuery(sql.toString(), qex, explicitClosed); @@ -682,7 +694,7 @@ public SQLException handleResultException( @Override public int getParamCount() { - return clientPrepareResult.getQueryParts().size() - 1; + return clientPrepareResult.getParamCount(); } @Override diff --git a/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java b/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java index a8eb3b5a4..38d20126a 100644 --- a/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java +++ b/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java @@ -55,6 +55,8 @@ import static org.junit.Assert.*; import java.sql.*; + +import org.junit.Assume; import org.junit.Test; import org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory; import org.mariadb.jdbc.util.Options; @@ -398,6 +400,39 @@ public void rewriteBatchedError() throws Exception { } } + @Test + public void rewriteErrorException() throws Exception { + Assume.assumeFalse(sharedOptions().useServerPrepStmts); + try (Connection connection = + setConnection("&rewriteBatchedStatements=true&dumpQueriesOnException")) { + ensureErrorException(connection); + } + try (Connection connection = + setConnection("&rewriteBatchedStatements=false&dumpQueriesOnException")) { + ensureErrorException(connection); + } + } + + private void ensureErrorException(Connection connection) throws SQLException { + PreparedStatement pstmt = + connection.prepareStatement("UPDATE unknownTable SET col1 = ?, col2 = 0 WHERE col3 = ?;"); + pstmt.setInt(1, 10); + pstmt.setInt(2, 20); + pstmt.addBatch(); + pstmt.setInt(1, 100); + pstmt.setInt(2, 200); + try { + pstmt.executeBatch(); + fail("Must have thrown error"); + } catch (SQLException sqle) { + assertTrue(sqle.getMessage(), sqle.getMessage().contains("doesn't exist")); + assertTrue( + sqle.getMessage(), + sqle.getMessage() + .contains("Query is: UPDATE unknownTable SET col1 = 10, col2 = 0 WHERE col3 = 20;")); + } + } + @Test public void testLastInsertId() throws Exception { assertTrue( From 864186974438331055fe19c5866f2ff59f3cf153 Mon Sep 17 00:00:00 2001 From: lnnwvr <57183704+lnnwvr@users.noreply.github.com> Date: Thu, 24 Sep 2020 13:11:16 +0200 Subject: [PATCH 20/25] added osgi related packege imports for gss The import package declarations seem to be necessary in an osgi environment, tested with karaf 4.x.x --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 327aa3322..324edcab8 100644 --- a/pom.xml +++ b/pom.xml @@ -180,7 +180,7 @@ org.mariadb.jdbc org.mariadb.jdbc - org.osgi.service.jdbc,org.osgi.framework,javax.naming,javax.management,javax.sql,javax.net;resolution:=optional,javax.net.ssl;resolution:=optional,javax.transaction.xa;resolution:=optional,waffle.windows.auth;resolution:=optional,waffle.windows.auth.impl;resolution:=optional + org.osgi.service.jdbc,org.osgi.framework,javax.naming,javax.management,javax.sql,javax.net;resolution:=optional,javax.net.ssl;resolution:=optional,javax.transaction.xa;resolution:=optional,waffle.windows.auth;resolution:=optional,waffle.windows.auth.impl;resolution:=optional,org.ietf.jgss;resolution:=optional,javax.security.auth.login;resolution:=optional org.mariadb.jdbc.internal.osgi.MariaDbActivator From c26c1623e976d6d4c8f144c39061e99689f0d1af Mon Sep 17 00:00:00 2001 From: rusher Date: Wed, 18 Nov 2020 16:16:11 +0100 Subject: [PATCH 21/25] [CONJ-838] replace 'slave' terminology by 'replica' Host description is now : [:] or address=(host=)[(port=)][(type=(master|replica) )] 'slave' will still work as an alias for 'replica' --- ...ailability-with-mariadb-connector-j.creole | 62 ++++++------ documentation/failover_loop.creole | 14 +-- .../use-mariadb-connector-j-driver.creole | 14 +-- .../java/org/mariadb/jdbc/HostAddress.java | 11 ++- src/main/java/org/mariadb/jdbc/UrlParser.java | 4 +- .../failover/AbstractMastersListener.java | 4 +- ...a => AbstractMastersReplicasListener.java} | 11 ++- .../jdbc/internal/failover/FailoverProxy.java | 14 +-- .../jdbc/internal/failover/Listener.java | 2 +- .../failover/impl/AuroraListener.java | 6 +- .../impl/MastersFailoverListener.java | 8 +- ...ener.java => MastersReplicasListener.java} | 34 +++---- .../internal/failover/tools/SearchFilter.java | 16 +-- .../protocol/AbstractConnectProtocol.java | 2 +- .../protocol/AbstractQueryProtocol.java | 6 +- .../internal/protocol/AuroraProtocol.java | 13 +-- ...ocol.java => MastersReplicasProtocol.java} | 37 +++---- .../org/mariadb/jdbc/internal/util/Utils.java | 8 +- .../util/constant/ParameterConstant.java | 2 +- .../org/mariadb/jdbc/util/DefaultOptions.java | 4 +- .../ClientPreparedStatementParsingTest.java | 1 - .../java/org/mariadb/jdbc/ConnectionTest.java | 2 +- .../org/mariadb/jdbc/ExecuteBatchTest.java | 2 +- .../java/org/mariadb/jdbc/JdbcParserTest.java | 54 +++++----- .../jdbc/failover/AuroraFailoverTest.java | 14 +-- .../jdbc/failover/BaseReplication.java | 98 +++++++++---------- .../failover/ReplicationFailoverTest.java | 14 +-- 27 files changed, 234 insertions(+), 223 deletions(-) rename src/main/java/org/mariadb/jdbc/internal/failover/{AbstractMastersSlavesListener.java => AbstractMastersReplicasListener.java} (95%) rename src/main/java/org/mariadb/jdbc/internal/failover/impl/{MastersSlavesListener.java => MastersReplicasListener.java} (97%) rename src/main/java/org/mariadb/jdbc/internal/protocol/{MastersSlavesProtocol.java => MastersReplicasProtocol.java} (89%) diff --git a/documentation/failover-and-high-availability-with-mariadb-connector-j.creole b/documentation/failover-and-high-availability-with-mariadb-connector-j.creole index 60a46bf1b..8866fecaf 100644 --- a/documentation/failover-and-high-availability-with-mariadb-connector-j.creole +++ b/documentation/failover-and-high-availability-with-mariadb-connector-j.creole @@ -16,39 +16,39 @@ Load balancing allows load (read and write) to be distributed over multiple serv = Replication cluster type In MariaDB (and MySQL) replication, there are 2 different replication roles: * Master role: Database server that permits read and write operations -* Slave role: Database server that permits only read operations +* Replica role: Database server that permits only read operations This document describes configuration and implementation for 3 types of clusters: * Multi-Master replication cluster. All hosts have a master replication role. (example : Galera) -* Master/slaves cluster: one host has the master replication role with multiple hosts in slave replication role. -* Hybrid cluster: multiple hosts in master replication role with multiple hosts in slave replication role. +* Master/replica cluster: one host has the master replication role with multiple hosts in replica replication role. +* Hybrid cluster: multiple hosts in master replication role with multiple hosts in replica role. = Load balancing implementation == Random picking -When initializing a connection or after a failed connection, the connector will attempt to connect to a host with a certain role (slave/master). +When initializing a connection or after a failed connection, the connector will attempt to connect to a host with a certain role (replica/master). The connection is selected randomly among the valid hosts. Thereafter, all statements will run on that database server until the connection will be closed (or fails). The load-balancing will includes a pooling mechanism. Example: when creating a pool of 60 connections, each one will use a random host. With 3 master hosts, the pool will have about 20 connections to each host. -== Master/slave distributed load +== Master/replica distributed load -For a cluster composed of masters and slaves on connection initialization, there will be 2 underlying connections: one with a master host, another with a slave host. Only one connection is used at a time. \\ +For a cluster composed of masters and replicas on connection initialization, there will be 2 underlying connections: one with a master host, another with a replica host. Only one connection is used at a time. \\ For a cluster composed of master hosts only, each connection has only one underlying connection. \\ The load will be distributed due to the random distribution of connections..\\ -== Master/slave connection selection +== Master/replica connection selection -It’s the application that has to decide to use master or slave connection (the master connection is set by default).\\ -Switching the type of connection is done by using JDBC [[http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#setReadOnly(boolean)|connection.setReadOnly(boolean readOnly)]] method. Setting read-only to true will use the slave connection, false, the master connection.\\ +It’s the application that has to decide to use master or replica connection (the master connection is set by default).\\ +Switching the type of connection is done by using JDBC [[http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#setReadOnly(boolean)|connection.setReadOnly(boolean readOnly)]] method. Setting read-only to true will use the replica connection, false, the master connection.\\ Example in standard java: {{{ -connection = DriverManager.getConnection("jdbc:mariadb:replication://master1,slave1/test"); +connection = DriverManager.getConnection("jdbc:mariadb:replication://master1,replica1/test"); stmt = connection.createStatement(); stmt.execute("SELECT 1"); // will execute query on the underlying master1 connection connection.setReadOnly(true); -stmt.execute("SELECT 1"); // will execute query on the underlying slave1 connection +stmt.execute("SELECT 1"); // will execute query on the underlying replica1 connection }}} Some frameworks render this kind of operation easier, as for example Spring [[http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html#readOnly--|@transactionnal]] readOnly parameter (since spring 3.0.1). @@ -66,7 +66,7 @@ public void createContacts() { } }}} -Generated Spring Data repository objects use the same logic: the find* method will use the slave connection, other use master connection without having to explicitly set that for each method. +Generated Spring Data repository objects use the same logic: the find* method will use the replica connection, other use master connection without having to explicitly set that for each method. On a cluster with master hosts only, the use of connection.setReadOnly(true) does not change the connection, but if the database version is 10.0.0 or higher, the session is set to readOnly if option assureReadOnly is set to true, which means that any write query will throw an exception. @@ -78,19 +78,19 @@ When no failover/high availability parameter is set, the failover support is bas When a failover /high availability parameter is set.Check the [[configuration]] section for an overview on how to set the parameters. There can be multiple fail causes. When a failure occurs many things will be done: -* The fail host address will be put on a blacklist (shared by JVM). This host will not be used for the amount of time defined by the “loadBalanceBlacklistTimeout” parameter (default to 50 seconds). The only time a blacklisted address can be used is if all host of the same type (master/slave) are blacklisted. +* The fail host address will be put on a blacklist (shared by JVM). This host will not be used for the amount of time defined by the “loadBalanceBlacklistTimeout” parameter (default to 50 seconds). The only time a blacklisted address can be used is if all host of the same type (master/replica) are blacklisted. * The connector will check the connection (with the mysql [[https://dev.mysql.com/doc/internals/en/com-ping.html|ping protocol]]). If the connection is back, is not read-only, and is in a transaction, the transaction will be rollbacked (there is no way to know if the last query has been received by the server and executed). -* If the failure relates to a slave connection +* If the failure relates to a replica connection * If the master connection is still active, the master connection will be used immediately. The query that was read-only will be relaunched and the connector will not throw any exception. - A "failover" thread will be launched to attempt to reconnect a slave host. + A "failover" thread will be launched to attempt to reconnect a replica host. (if the query was a prepared query, this query will be re-prepared before execution) - * If the master connection is not active, the driver will attempt to create a new master or slave connection with a [[#connection-loop|connection loop]]. + * If the master connection is not active, the driver will attempt to create a new master or replica connection with a [[#connection-loop|connection loop]]. if any connection is found, the query will be relaunched, if not, an SQLException with sqlState like “08XXX” will be thrown. * If the failure relates to a master connection, the driver will attempt to create a new master connection with a [[#connection-loop|connection loop]], so the connection object will be immediately reusable.\\ * on failure, an SQLException with be thrown with SQLState "08XXX". If using a pool, this connection will be discarded. * on success, - * if possible query will be relaunched without throwing error (if was using a slave connection, or was a SELECT query not in a transaction for example). + * if possible query will be relaunched without throwing error (if was using a replica connection, or was a SELECT query not in a transaction for example). * if not possible, an SQLException with be thrown with SQLState "25S03". * When throwing an SQLException with SQLState "08XXX", the connection will be marked as closed. * A “failover” thread will be launched to attempt to reconnect failing connection if connection is not closed. @@ -98,7 +98,7 @@ There can be multiple fail causes. When a failure occurs many things will be don It’s up to the application to take measures to handle SQLException. See details in [[#application-concerns|application concerns]]. #Connection loop -When initializing a connection or after a failure, the driver will launch a connection loop the only case when this connection loop will not be executed is when the failure occurred on a slave with an active master. +When initializing a connection or after a failure, the driver will launch a connection loop the only case when this connection loop will not be executed is when the failure occurred on a replica with an active master. This connection loop will try to connect to a valid host until finding a new connection or until the number of connections exceed the parameter “retriesAllDown” value (default to 120). This loop will attempt to connect sequentially to hosts in the following order: @@ -107,10 +107,10 @@ For a master connection : * random connect to master host not blacklisted * random connect to master blacklisted -For a slave connection : -* random connect to slave host not blacklisted +For a replica connection : +* random connect to replica host not blacklisted * random connect to master host not blacklisted (if no active master connection) -* random connect to slave blacklisted +* random connect to replica blacklisted * random connect to master host blacklisted (if no active master connection) The sequence stops as soon as all the underlying needed connections are found. Every time an attempt fails, the host will be blacklisted. If after an entire loop a master connection is missing, the connection will be marked as closed. @@ -118,9 +118,9 @@ If after an entire loop a master connection is missing, the connection will be m =Additional threads ==Failover reconnection threads -A thread pool is created in case of a master/slave cluster, the size is defined according to the number of connection. -After a failure on a slave connection, readonly operations are temporary executed on the master connection. Some “failover threads” will try to reconnect the failed underlying connections. -When a new slave connection is retrieved, this one will be immediately used if connection was still in read-only mode.\\ +A thread pool is created in case of a master/replica cluster, the size is defined according to the number of connection. +After a failure on a replica connection, readonly operations are temporary executed on the master connection. Some “failover threads” will try to reconnect the failed underlying connections. +When a new replica connection is retrieved, this one will be immediately used if connection was still in read-only mode.\\ More details in [[failover_loop.creole|Failover loop threads]]. @@ -173,7 +173,7 @@ Each parameter corresponds to a specific use case: |=Failover option|=Description| | **failover** | High availability (random picking connection initialisation) with failover support for master replication cluster (exemple Galera). \\* Since 1.2.0*| | **sequential** |Failover support for master replication cluster (for example Galera) **without** High availability. \\the host will be connected in the order in which they were declared.\\\\Example when using the jdbc url string "jdbc:mariadb:replication:host1,host2,host3/test" : \\When connecting, the driver will always try first host1, and if not available host2 and following. After a host fail, the driver will reconnect according to this order.\\*Since 1.3.0*| -| **replication** | High availability (random picking connection initialisation) with failover support for master/slaves replication cluster (one or multiple master).\\* Since 1.2.0*| +| **replication** | High availability (random picking connection initialisation) with failover support for master/replica replication cluster (one or multiple master).\\* Since 1.2.0*| | **aurora** | High availability (random picking connection initialisation) with failover support for Amazon Aurora replication cluster.\\* Since 1.2.0*| @@ -182,7 +182,7 @@ Each parameter corresponds to a specific use case: |=Option|=Description| |autoReconnect|With basic failover only, if true, will attempt to recreate connection after a failover.\\*Default is false. Since 1.1.7*| |retriesAllDown|When searching a valid host, maximum number of connection attempts before throwing an exception.\\*Default: 120. Since 1.2.0| -|failoverLoopRetries|When searching silently for a valid host, maximum number of connection attempts.\\This differ from "retriesAllDown" parameter, because this silent search is for example used after a disconnection of a slave connection when using the master connection.\\*Default: 120. Since 1.2.0*| +|failoverLoopRetries|When searching silently for a valid host, maximum number of connection attempts.\\This differ from "retriesAllDown" parameter, because this silent search is for example used after a disconnection of a replica connection when using the master connection.\\*Default: 120. Since 1.2.0*| |validConnectionTimeout|With multiple hosts, after this time in seconds has elapsed it’s verified that the connections haven’t been lost.\\When 0, no verification will be done.\\*Default:120 seconds. Since 1.2.0*| |loadBalanceBlacklistTimeout|When a connection fails, this host will be blacklisted during the "loadBalanceBlacklistTimeout" amount of time.\\When connecting to a host, the driver will try to connect to a host in the list of not blacklisted hosts and after that only on blacklisted ones if none has been found before that.\\This blacklist is shared inside the classloader.\\*Default: 50 seconds. Since 1.2.0*| |assureReadOnly|If true, in high availability, and switching to a read-only host, assure that this host is in read-only mode by setting session read-only.\\alias "readOnlyPropagatesToServer" worked to for compatibility\\*Default to false.\\ Since 1.3.0*| @@ -190,7 +190,7 @@ Each parameter corresponds to a specific use case: =Specifics for Amazon Aurora -Amazon Aurora is a Master/Slaves cluster composed of one master instance with a maximum of 15 slave instances. Amazon Aurora includes automatic promotion of a slave instance in case of the master instance failing. The MariaDB connector/J implementation for Aurora is specific to handle this automatic failover.\\ +Amazon Aurora is a Master/Replicas cluster composed of one master instance with a maximum of 15 replica instances. Amazon Aurora includes automatic promotion of a replica instance in case of the master instance failing. The MariaDB connector/J implementation for Aurora is specific to handle this automatic failover.\\ To permit development/integration on a single-node cluster, only one host can be defined. In this case, the driver behaves as for the configuration **failover**. @@ -215,7 +215,7 @@ There is another endpoint named "cluster endpoint" (format `xxx.cluster-yyy.zzz. In version before 1.5.1, cluster endpoint use was discouraged, since when a failover occur, this cluster endpoint can point for a limited time to a host that isn't the current master anymore. Old recommandation was to list all specific end-points. This kind of url string will still work, but now, recommended url string has to use only cluster endpoint. -Driver will automatically discover master and slaves of this cluster from current cluster end-point during connection time. This permit to add new replicas to the cluster instance will be discovered without changing driver configuration. +Driver will automatically discover master and replicas of this cluster from current cluster end-point during connection time. This permit to add new replicas to the cluster instance will be discovered without changing driver configuration. This discovery append at connection time, so if you are using pool framework, check if this framework as a property that controls the maximum lifetime of a connection in the pool, and set a value to avoid infinite lifetime. When this lifetime is reached, pool will discarded the current connection, and create a new one (if needed). New connections will use the new replicas. (If connections are never discarded, new replicas will begin be used only when a failover occur) @@ -245,12 +245,12 @@ Note that the option "createDatabaseIfNotExist=true" causes reader instances to ==Aurora connection loop -When searching for the master instance and connect to a slave instance, the connection order will be: +When searching for the master instance and connect to a replica instance, the connection order will be: * Every Aurora instance knows the hostname of the current master. If the host has been described using their instance endpoint, that will permit to know the master instance and connect directly to it. -* If this isn’t the current master (because using IP, or possible after a failover between step 2 and 3), the loop will connect randomly the other not blacklisted instance (minus the current slave instance) +* If this isn’t the current master (because using IP, or possible after a failover between step 2 and 3), the loop will connect randomly the other not blacklisted instance (minus the current replica instance) * Connect randomly to a blacklisted instance. -When searching for a slave instance, the loop will connection order will be: +When searching for a replica instance, the loop will connection order will be: * random not blacklisted instances (excluding the current host if connected) * random blacklisted instances The loop will retry until the connections are found or parameter “retriesAllDown” is exceeded. diff --git a/documentation/failover_loop.creole b/documentation/failover_loop.creole index 26460793a..e0860cf8a 100644 --- a/documentation/failover_loop.creole +++ b/documentation/failover_loop.creole @@ -5,26 +5,26 @@ = Failover reconnection -//** This concern only master/slave cluster **// +//** This concern only master/replica cluster **// -On a master/slave cluster, driver will use underlying 2 connections: one to a master instance, one to a slave instance. +On a master/replica cluster, driver will use underlying 2 connections: one to a master instance, one to a replica instance. When one of the connection fail, if driver does need it at once, it will create a new connection immediately before re-executing query if possible.\\ If the failed connection is not needed immediately, this driver will subscribe to the "failover reconnection" that will be handle in other threads. Failover threads will attempt to create new connection to replace failing ones, so the interruption is minimal for the queries in progress. When client asked to use a failed connection, the new connection created by failover thread will replace the failed one. -Example: after a failure on a slave connection, readonly operations are temporary executed on the master connection to avoid interruption client side. -Failover thread will then create a new slave connection that will replace the failed one. Next query will use the new slave connection. +Example: after a failure on a replica connection, readonly operations are temporary executed on the master connection to avoid interruption client side. +Failover thread will then create a new replica connection that will replace the failed one. Next query will use the new replica connection. -A pool of threads is initialized when using a master/slave configuration. The pool size evolves according to the number of connection. +A pool of threads is initialized when using a master/replica configuration. The pool size evolves according to the number of connection. == Illustration -Here is an example of a failover on a aurora cluster of 3 instances (one master and 2 slaves).\\ +Here is an example of a failover on a aurora cluster of 3 instances (one master and 2 replicas).\\ (Source code https://github.com/rusher/connector-aurora-fail-test/tree/master) We can see 2 kinds of threads : -* Threads named "test-thread-XXX" do 130 queries "SELECT 1". 1/3 use master connection, 2/3 slave connection. +* Threads named "test-thread-XXX" do 130 queries "SELECT 1". 1/3 use master connection, 2/3 replica connection. * Threads "mariaDb-reconnection-XXX" are created by the driver to handle failover. ==== Colour signification: diff --git a/documentation/use-mariadb-connector-j-driver.creole b/documentation/use-mariadb-connector-j-driver.creole index 1bab41368..8bef8feca 100644 --- a/documentation/use-mariadb-connector-j-driver.creole +++ b/documentation/use-mariadb-connector-j-driver.creole @@ -65,13 +65,13 @@ jdbc:(mysql|mariadb):[replication:|failover:|sequential:|aurora:]//[:] or address=(host=)[(port=)][(type=(master|slave))] +[:] or address=(host=)[(port=)][(type=(master|replica))] }}} Host must be a DNS name or IP address. In case of ipv6 and simple host description, the IP address must be written inside brackets. The default port is {{{3306}}}. The default type is {{{master}}}. If {{{replication}}} failover is -set, by default the first host is master, and the others are slaves. +set, by default the first host is master, and the others are replicas. Examples : * {{{localhost:3306}}} @@ -92,7 +92,7 @@ Failover was introduced in Connector/J 1.2.0. |=sequential |Failover support for master replication cluster (for example Galera) without High availability. The hosts will be connected in the order in which they were declared.\\\\Example when using the jdbc url string "jdbc:mariadb:replication:host1,host2,host3/test" : \\When connecting, the driver will always first try host1, and if not available host2 and so on. After a host fail, the driver will reconnect according to this order. \\//since 1.3.0//| |=failover | High availability (random picking connection initialisation) with failover support for master replication cluster (for example Galera). \\//since 1.2.0//| -|=replication | High availability (random picking connection initialisation) with failover support for master/slave replication cluster (one or multiple masters) \\//since 1.2.0//| +|=replication | High availability (random picking connection initialisation) with failover support for master/replica replication cluster (one or multiple masters) \\//since 1.2.0//| |=aurora | High availability (random picking connection initialisation) with failover support for Amazon Aurora replication cluster \\//since 1.2.0//| See [[failover-and-high-availability-with-mariadb-connector-j|failover description]] for more information. @@ -192,13 +192,13 @@ See [[use-mariadb-connector-j-driver.creole#using-pooling|using pooling]] for mo \\\\ == Failover/High availability URL parameters -|=autoReconnect|With basic failover: if true, will attempt to recreate connection after a failover. \\With standard failover: if true, will attempt to recreate connection even if there is a temporary solution (like using a master connection temporary until reconnect to a slave connection) \\//Default is false. Since 1.1.7//| +|=autoReconnect|With basic failover: if true, will attempt to recreate connection after a failover. \\With standard failover: if true, will attempt to recreate connection even if there is a temporary solution (like using a master connection temporary until reconnect to a replica connection) \\//Default is false. Since 1.1.7//| |=retriesAllDown|When searching a valid host, maximum number of connection attempts before throwing an exception.\\//Default: 120 seconds. Since 1.2.0//| -|=failoverLoopRetries|When searching silently for a valid host, maximum number of connection attempts.\\This differs from the "retriesAllDown" parameter because this silent search is for example used after a disconnection of a slave connection when using the master connection\\//Default: 120. Since 1.2.0//| +|=failoverLoopRetries|When searching silently for a valid host, maximum number of connection attempts.\\This differs from the "retriesAllDown" parameter because this silent search is for example used after a disconnection of a replica connection when using the master connection\\//Default: 120. Since 1.2.0//| |=validConnectionTimeout|With multiple hosts, after this time in seconds has elapsed, verifies that the connections haven’t been lost.\\When 0, no verification will be done. \\//Default:120 seconds. Since 1.2.0//| |=loadBalanceBlacklistTimeout|When a connection fails, this host will be blacklisted for the "loadBalanceBlacklistTimeout" amount of time.\\When connecting to a host, the driver will try to connect to a host in the list of non-blacklisted hosts and, only if none are found, attempt blacklisted ones.\\This blacklist is shared inside the classloader.\\//Default: 50 seconds. Since 1.2.0//| |=assureReadOnly|If true, in high availability, and switching to a read-only host, assure that this host is in read-only mode by setting the session to read-only.\\//Default to false. Since 1.3.0//| -|=allowMasterDownConnection|When using master/slave configuration, permit to create connection when master is down. If all masters are down, default connection is then a slave and Connection.isReadOnly() will then return true. \\//Default: false. Since 2.2.0//| +|=allowMasterDownConnection|When using master/replica configuration, permit to create connection when master is down. If all masters are down, default connection is then a replica and Connection.isReadOnly() will then return true. \\//Default: false. Since 2.2.0//| |=galeraAllowedState|Usually, Connection.isValid just send an empty packet to server, and server send a small response to ensure connectivity. When this option is set, connector will ensure server that "wsrep_local_state" correspond to allowed values (separated by comma). example "4,5".\\//Default: empty. Since 2.2.5//| \\\\ @@ -349,7 +349,7 @@ This reset goal is that next Connection get from pool has the same state as a ne Reset operations : * rollback remaining active transaction * reuse the configured database if changed -* default connection read-only state to false (master in a masters/slaves configuration) if changed +* default connection read-only state to false (master in a masters/replicas configuration) if changed * re-initialize socket timeout if changed * autocommit reset to default * Transaction Isolation if changed diff --git a/src/main/java/org/mariadb/jdbc/HostAddress.java b/src/main/java/org/mariadb/jdbc/HostAddress.java index ca8c3a0b2..4d754c243 100644 --- a/src/main/java/org/mariadb/jdbc/HostAddress.java +++ b/src/main/java/org/mariadb/jdbc/HostAddress.java @@ -144,7 +144,7 @@ public static List parse(String spec, HaMode haMode) { if (i == 0 && arr.get(i).type == null) { arr.get(i).type = ParameterConstant.TYPE_MASTER; } else if (i != 0 && arr.get(i).type == null) { - arr.get(i).type = ParameterConstant.TYPE_SLAVE; + arr.get(i).type = ParameterConstant.TYPE_REPLICA; } } } @@ -196,10 +196,11 @@ private static HostAddress parseParameterHostAddress(String str) { result.host = value.replace("[", "").replace("]", ""); } else if ("port".equals(key)) { result.port = getPort(value); - } else if ("type".equals(key) - && (value.equals(ParameterConstant.TYPE_MASTER) - || value.equals(ParameterConstant.TYPE_SLAVE))) { - result.type = value; + } else if ("type".equals(key)) { + if (value.equals(ParameterConstant.TYPE_MASTER) + || value.equals(ParameterConstant.TYPE_REPLICA)) { + result.type = value; + } else if ("slave".equals(value)) result.type = ParameterConstant.TYPE_REPLICA; } } return result; diff --git a/src/main/java/org/mariadb/jdbc/UrlParser.java b/src/main/java/org/mariadb/jdbc/UrlParser.java index 3de640f83..c3f26b872 100644 --- a/src/main/java/org/mariadb/jdbc/UrlParser.java +++ b/src/main/java/org/mariadb/jdbc/UrlParser.java @@ -81,7 +81,7 @@ * (for example localhost:3306)
*
* - complex :
- * {@code address=[(type=(master|slave))][(port=)](host=)}
+ * {@code address=[(type=(master|replica))][(port=)](host=)}
*
*
* type is by default master
@@ -94,7 +94,7 @@ *

Some examples :
* {@code jdbc:mariadb://localhost:3306/database?user=greg&password=pass}
* {@code - * jdbc:mariadb://address=(type=master)(host=master1),address=(port=3307)(type=slave)(host=slave1)/database?user=greg&password=pass} + * jdbc:mariadb://address=(type=master)(host=master1),address=(port=3307)(type=replica)(host=replica1)/database?user=greg&password=pass} *
*/ public class UrlParser implements Cloneable { diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java index 456e16a99..df56bb8d5 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java @@ -371,7 +371,7 @@ public boolean isQueryRelaunchable(Method method, Object[] args) { switch (method.getName()) { case "executeQuery": if (!((Boolean) args[0])) { - return true; // launched on slave connection + return true; // launched on replica connection } if (args[2] instanceof String) { return ((String) args[2]).toUpperCase(Locale.ROOT).startsWith("SELECT"); @@ -385,7 +385,7 @@ public boolean isQueryRelaunchable(Method method, Object[] args) { break; case "executePreparedQuery": if (!((Boolean) args[0])) { - return true; // launched on slave connection + return true; // launched on replica connection } ServerPrepareResult serverPrepareResult = (ServerPrepareResult) args[1]; return (serverPrepareResult.getSql()).toUpperCase(Locale.ROOT).startsWith("SELECT"); diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersSlavesListener.java b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersReplicasListener.java similarity index 95% rename from src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersSlavesListener.java rename to src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersReplicasListener.java index 719cc1498..44fcf8c93 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersSlavesListener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersReplicasListener.java @@ -63,9 +63,10 @@ import org.mariadb.jdbc.internal.protocol.Protocol; import org.mariadb.jdbc.internal.util.pool.GlobalStateInfo; -public abstract class AbstractMastersSlavesListener extends AbstractMastersListener { +public abstract class AbstractMastersReplicasListener extends AbstractMastersListener { - private static final Logger logger = LoggerFactory.getLogger(AbstractMastersSlavesListener.class); + private static final Logger logger = + LoggerFactory.getLogger(AbstractMastersReplicasListener.class); // These reference are when failloop reconnect failing connection, but lock is already held by // another thread (query in progress), so switching the connection wait for the query to be // finish. @@ -77,13 +78,13 @@ public abstract class AbstractMastersSlavesListener extends AbstractMastersListe /* =========================== Failover variables ========================================= */ private volatile long secondaryHostFailNanos = 0; - protected AbstractMastersSlavesListener(UrlParser urlParser, final GlobalStateInfo globalInfo) { + protected AbstractMastersReplicasListener(UrlParser urlParser, final GlobalStateInfo globalInfo) { super(urlParser, globalInfo); this.secondaryHostFail.set(true); } /** - * Handle failover on master or slave connection. + * Handle failover on master or replica connection. * * @param method called method * @param args methods parameters @@ -168,7 +169,7 @@ public long getSecondaryHostFailNanos() { } /** - * Set slave connection lost variables. + * Set replica connection lost variables. * * @return true if fail wasn't seen before */ diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java b/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java index 54fe2ecf1..42d11e726 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/FailoverProxy.java @@ -229,14 +229,14 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl if (!mustBeOnMaster && serverPrepareResult.getUnProxiedProtocol().isMasterConnection() && !this.listener.hasHostFail()) { - // PrepareStatement was to be executed on slave, but since a failover was running on - // master connection. Slave connection is up - // again, so has to be re-prepared on slave + // PrepareStatement was to be executed on replica, but since a failover was running on + // master connection. Replica connection is up + // again, so has to be re-prepared on replica try { logger.trace( - "re-prepare query \"{}\" on slave (was " + "temporary on master since failover)", + "re-prepare query \"{}\" on replica (was temporary on master since failover)", serverPrepareResult.getSql()); - this.listener.rePrepareOnSlave(serverPrepareResult, false); + this.listener.rePrepareOnReplica(serverPrepareResult, false); } catch (SQLException q) { // error during re-prepare, will do executed on master. } @@ -285,7 +285,7 @@ && hasToHandleFailover((SQLException) e.getTargetException())) { throw e; } case METHOD_RESET: - // listener will report reset on any active connections (Master/slave) + // listener will report reset on any active connections (Master/replica) listener.reset(); return null; default: @@ -326,7 +326,7 @@ private Object executeInvocation(Method method, Object[] args, boolean isSecondE // error is "The MariaDB server is running with the %s option so it cannot execute this // statement" - // checking that server was master has not been demote to slave without resetting + // checking that server was master has not been demote to replica without resetting // connections if (queryException.getErrorCode() == 1290 && !isSecondExecution diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java b/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java index 092618a24..fc388078a 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/Listener.java @@ -167,7 +167,7 @@ void prolog(long maxRows, MariaDbConnection connection, MariaDbStatement stateme boolean checkMasterStatus(SearchFilter searchFilter); - void rePrepareOnSlave(ServerPrepareResult oldServerPrepareResult, boolean mustExecuteOnMaster) + void rePrepareOnReplica(ServerPrepareResult oldServerPrepareResult, boolean mustExecuteOnMaster) throws SQLException; void reset() throws SQLException; diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/impl/AuroraListener.java b/src/main/java/org/mariadb/jdbc/internal/failover/impl/AuroraListener.java index d85da16cb..1603cb85f 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/impl/AuroraListener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/impl/AuroraListener.java @@ -71,7 +71,7 @@ import org.mariadb.jdbc.internal.util.dao.ReconnectDuringTransactionException; import org.mariadb.jdbc.internal.util.pool.GlobalStateInfo; -public class AuroraListener extends MastersSlavesListener { +public class AuroraListener extends MastersReplicasListener { private static final Logger logger = Logger.getLogger(AuroraListener.class.getName()); private final Pattern auroraDnsPattern = @@ -158,7 +158,7 @@ public void reconnectFailedConnection(SearchFilter initialSearchFilter) throws S if (!searchFilter.isInitialConnection() && (isExplicitClosed() || (searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) - || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail())) { + || searchFilter.isFineIfFoundOnlyReplica() && !isSecondaryHostFail())) { return; } @@ -166,7 +166,7 @@ public void reconnectFailedConnection(SearchFilter initialSearchFilter) throws S try { checkWaitingConnection(); if ((searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) - || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail()) { + || searchFilter.isFineIfFoundOnlyReplica() && !isSecondaryHostFail()) { return; } } catch (ReconnectDuringTransactionException e) { diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java index 9cf7aa22f..96316762b 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java @@ -110,7 +110,7 @@ public void initializeConnection() throws SQLException { */ public void preExecute() throws SQLException { lastQueryNanos = System.nanoTime(); - // if connection is closed or failed on slave + // if connection is closed or failed on replica if (this.currentProtocol != null && this.currentProtocol.isClosed()) { preAutoReconnect(); } @@ -338,9 +338,9 @@ public boolean checkMasterStatus(SearchFilter searchFilter) { return false; } - public void rePrepareOnSlave( - ServerPrepareResult oldServerPrepareResult, boolean mustExecuteOnSlave) { - // no slave + public void rePrepareOnReplica( + ServerPrepareResult oldServerPrepareResult, boolean mustExecuteOnReplica) { + // no replica } /** diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersReplicasListener.java similarity index 97% rename from src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java rename to src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersReplicasListener.java index f495b67f8..a0039c6b8 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersReplicasListener.java @@ -66,13 +66,13 @@ import org.mariadb.jdbc.MariaDbConnection; import org.mariadb.jdbc.MariaDbStatement; import org.mariadb.jdbc.UrlParser; -import org.mariadb.jdbc.internal.failover.AbstractMastersSlavesListener; +import org.mariadb.jdbc.internal.failover.AbstractMastersReplicasListener; import org.mariadb.jdbc.internal.failover.HandleErrorResult; import org.mariadb.jdbc.internal.failover.thread.FailoverLoop; import org.mariadb.jdbc.internal.failover.tools.SearchFilter; import org.mariadb.jdbc.internal.logging.Logger; import org.mariadb.jdbc.internal.logging.LoggerFactory; -import org.mariadb.jdbc.internal.protocol.MastersSlavesProtocol; +import org.mariadb.jdbc.internal.protocol.MastersReplicasProtocol; import org.mariadb.jdbc.internal.protocol.Protocol; import org.mariadb.jdbc.internal.util.dao.ReconnectDuringTransactionException; import org.mariadb.jdbc.internal.util.dao.ServerPrepareResult; @@ -81,10 +81,10 @@ import org.mariadb.jdbc.internal.util.scheduler.SchedulerServiceProviderHolder; /** this class handle the operation when multiple hosts. */ -public class MastersSlavesListener extends AbstractMastersSlavesListener { +public class MastersReplicasListener extends AbstractMastersReplicasListener { private static final AtomicInteger listenerCount = new AtomicInteger(); - private static final Logger logger = LoggerFactory.getLogger(MastersSlavesListener.class); + private static final Logger logger = LoggerFactory.getLogger(MastersReplicasListener.class); private static DynamicSizedSchedulerInterface dynamicSizedScheduler; static { @@ -101,7 +101,7 @@ public class MastersSlavesListener extends AbstractMastersSlavesListener { * @param urlParser connection string object. * @param globalInfo server global variables information */ - public MastersSlavesListener(final UrlParser urlParser, final GlobalStateInfo globalInfo) { + public MastersReplicasListener(final UrlParser urlParser, final GlobalStateInfo globalInfo) { super(urlParser, globalInfo); if (dynamicSizedScheduler.isTerminated()) { loadScheduler(); @@ -402,7 +402,7 @@ public void preAbort() { public void preExecute() throws SQLException { lastQueryNanos = System.nanoTime(); checkWaitingConnection(); - // if connection is closed or failed on slave + // if connection is closed or failed on replica if (this.currentProtocol != null && (this.currentProtocol.isClosed() || (!currentReadOnlyAsked && !currentProtocol.isMasterConnection()))) { @@ -485,7 +485,7 @@ public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLExcep if (!searchFilter.isInitialConnection() && (isExplicitClosed() || (searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) - || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail())) { + || searchFilter.isFineIfFoundOnlyReplica() && !isSecondaryHostFail())) { return; } // check if a connection has been retrieved by failoverLoop during lock @@ -493,7 +493,7 @@ public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLExcep try { checkWaitingConnection(); if ((searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) - || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail()) { + || searchFilter.isFineIfFoundOnlyReplica() && !isSecondaryHostFail()) { return; } } catch (ReconnectDuringTransactionException e) { @@ -533,7 +533,7 @@ public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLExcep // and ping master connection fail a few millissecond after, // resulting a masterConnection not initialized. do { - MastersSlavesProtocol.loop(this, globalInfo, loopAddress, searchFilter); + MastersReplicasProtocol.loop(this, globalInfo, loopAddress, searchFilter); // close loop if all connection are retrieved if (!searchFilter.isFailoverLoop()) { try { @@ -664,7 +664,7 @@ public void lockAndSwitchSecondary(Protocol newSecondaryProtocol) throws SQLExce currentProtocol = newSecondaryProtocol; } - // set new found connection as slave connection. + // set new found connection as replica connection. this.secondaryProtocol = newSecondaryProtocol; if (urlParser.getOptions().assureReadOnly) { setSessionReadOnly(true, this.secondaryProtocol); @@ -710,7 +710,7 @@ public void switchReadOnlyConnection(Boolean mustBeReadOnly) throws SQLException } } } - // stay on master connection, since slave connection is fail + // stay on master connection, since replica connection is fail FailoverLoop.addListener(this); } } else { @@ -798,7 +798,7 @@ public HandleErrorResult primaryFail( masterProtocol.close(); } - // fail on slave if parameter permit so + // fail on replica if parameter permit so if (urlParser.getOptions().failOnReadOnly && !isSecondaryHostFail()) { try { if (this.secondaryProtocol != null && this.secondaryProtocol.ping()) { @@ -959,7 +959,7 @@ public HandleErrorResult secondaryFail(Method method, Object[] args, boolean kil } FailoverLoop.addListener(this); logger.info( - "Connection to slave lost, using master connection" + "Connection to replica lost, using master connection" + ", query is re-execute on master server without throwing exception"); return relaunchOperation( method, args); // relaunched result if the result was not crashing the master @@ -990,7 +990,7 @@ public HandleErrorResult secondaryFail(Method method, Object[] args, boolean kil } logger.info( - "Connection to slave lost, new slave {}, conn={} found" + "Connection to replica lost, new replica {}, conn={} found" + ", query is re-execute on new server without throwing exception", currentProtocol.getHostAddress(), currentProtocol.getServerThreadId()); @@ -1048,7 +1048,7 @@ public boolean checkMasterStatus(SearchFilter searchFilter) { } @Override - public void rePrepareOnSlave(ServerPrepareResult oldServerPrepareResult, boolean mustBeOnMaster) + public void rePrepareOnReplica(ServerPrepareResult oldServerPrepareResult, boolean mustBeOnMaster) throws SQLException { if (isSecondaryHostFail()) { Protocol waitingProtocol = waitNewSecondaryProtocol.getAndSet(null); @@ -1065,7 +1065,7 @@ public void rePrepareOnSlave(ServerPrepareResult oldServerPrepareResult, boolean } if (secondaryProtocol != null && !isSecondaryHostFail()) { - // prepare on slave + // prepare on replica ServerPrepareResult serverPrepareResult = secondaryProtocol.prepare(oldServerPrepareResult.getSql(), mustBeOnMaster); @@ -1111,7 +1111,7 @@ public List connectedHosts() { } /** - * Reset state of master and slave connection. + * Reset state of master and replica connection. * * @throws SQLException if command fail. */ diff --git a/src/main/java/org/mariadb/jdbc/internal/failover/tools/SearchFilter.java b/src/main/java/org/mariadb/jdbc/internal/failover/tools/SearchFilter.java index 217f5358c..8d6fe3a32 100644 --- a/src/main/java/org/mariadb/jdbc/internal/failover/tools/SearchFilter.java +++ b/src/main/java/org/mariadb/jdbc/internal/failover/tools/SearchFilter.java @@ -55,7 +55,7 @@ public class SearchFilter { private boolean fineIfFoundOnlyMaster; - private boolean fineIfFoundOnlySlave; + private boolean fineIfFoundOnlyReplica; private boolean initialConnection; private boolean failoverLoop; @@ -67,11 +67,11 @@ public SearchFilter() { * Constructor. * * @param fineIfFoundOnlyMaster stop searching if master found - * @param fineIfFoundOnlySlave stop searching if slave found + * @param fineIfFoundOnlyReplica stop searching if replica found */ - public SearchFilter(boolean fineIfFoundOnlyMaster, boolean fineIfFoundOnlySlave) { + public SearchFilter(boolean fineIfFoundOnlyMaster, boolean fineIfFoundOnlyReplica) { this.fineIfFoundOnlyMaster = fineIfFoundOnlyMaster; - this.fineIfFoundOnlySlave = fineIfFoundOnlySlave; + this.fineIfFoundOnlyReplica = fineIfFoundOnlyReplica; } /** @@ -91,8 +91,8 @@ public boolean isFineIfFoundOnlyMaster() { return fineIfFoundOnlyMaster; } - public boolean isFineIfFoundOnlySlave() { - return fineIfFoundOnlySlave; + public boolean isFineIfFoundOnlyReplica() { + return fineIfFoundOnlyReplica; } public boolean isFailoverLoop() { @@ -108,8 +108,8 @@ public String toString() { return "SearchFilter{" + ", fineIfFoundOnlyMaster=" + fineIfFoundOnlyMaster - + ", fineIfFoundOnlySlave=" - + fineIfFoundOnlySlave + + ", fineIfFoundOnlyReplica=" + + fineIfFoundOnlyReplica + ", initialConnection=" + initialConnection + ", failoverLoop=" diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java index cab8612b6..bbca4659a 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java @@ -1432,7 +1432,7 @@ public HostAddress getHostAddress() { public void setHostAddress(HostAddress host) { this.currentHost = host; - this.readOnly = ParameterConstant.TYPE_SLAVE.equals(this.currentHost.type); + this.readOnly = ParameterConstant.TYPE_REPLICA.equals(this.currentHost.type); } public String getHost() { diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java index 4b1c007cc..f86f6c6e6 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java @@ -846,9 +846,9 @@ public int getTotalExecutionNumber() { *

For failover, two additional information are in the result-set object : - current connection * : Since server maintain a state of this prepare statement, all query will be executed on this * particular connection. - executeOnMaster : state of current connection when creating this - * prepareStatement (if was on master, will only be executed on master. If was on a slave, can be - * execute temporary on master, but we keep this flag, so when a slave is connected back to - * relaunch this query on slave) + * prepareStatement (if was on master, will only be executed on master. If was on a replica, can + * be execute temporary on master, but we keep this flag, so when a replica is connected back to + * relaunch this query on replica) * * @param sql the query * @param executeOnMaster state of current connection when creating this prepareStatement diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AuroraProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AuroraProtocol.java index 4359c764c..a23b933c3 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AuroraProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AuroraProtocol.java @@ -68,7 +68,7 @@ import org.mariadb.jdbc.internal.io.LruTraceCache; import org.mariadb.jdbc.internal.util.pool.GlobalStateInfo; -public class AuroraProtocol extends MastersSlavesProtocol { +public class AuroraProtocol extends MastersReplicasProtocol { public AuroraProtocol( final UrlParser url, @@ -197,7 +197,7 @@ public static void loop( } else if (!protocol.isMasterConnection()) { if (listener.isSecondaryHostFailReconnect()) { - // in case cluster DNS is currently pointing to a slave host + // in case cluster DNS is currently pointing to a replica host if (listener.getUrlParser().getHostAddresses().size() <= 1 && protocol.getHostAddress().equals(listener.getClusterHostAddress())) { listener.retrieveAllEndpointsAndSet(protocol); @@ -225,7 +225,7 @@ public static void loop( loopAddresses.remove(probableMasterHost); AuroraProtocol.searchProbableMaster(listener, globalInfo, probableMasterHost); if (listener.isMasterHostFailReconnect() - && searchFilter.isFineIfFoundOnlySlave()) { + && searchFilter.isFineIfFoundOnlyReplica()) { return; } } @@ -247,7 +247,7 @@ public static void loop( return; } - // in case master not found but slave is , and allowing master down + // in case master not found but replica is , and allowing master down if (loopAddresses.isEmpty() && (listener.isMasterHostFailReconnect() && listener.urlParser.getOptions().allowMasterDownConnection @@ -255,14 +255,15 @@ public static void loop( return; } - // on connection and all slaves have been tested, use master if on + // on connection and all replicas have been tested, use master if on if (loopAddresses.isEmpty() && searchFilter.isInitialConnection() && !listener.isMasterHostFailReconnect()) { return; } - // if server has try to connect to all host, and there is remaining master or slave that fail + // if server has try to connect to all host, and there is remaining master or replica that + // fail // add all servers back to continue looping until maxConnectionTry is reached if (loopAddresses.isEmpty() && !searchFilter.isFailoverLoop() && maxConnectionTry > 0) { resetHostList(listener, loopAddresses); diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/MastersSlavesProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/MastersReplicasProtocol.java similarity index 89% rename from src/main/java/org/mariadb/jdbc/internal/protocol/MastersSlavesProtocol.java rename to src/main/java/org/mariadb/jdbc/internal/protocol/MastersReplicasProtocol.java index 96413846b..1e093b396 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/MastersSlavesProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/MastersReplicasProtocol.java @@ -58,17 +58,17 @@ import org.mariadb.jdbc.HostAddress; import org.mariadb.jdbc.UrlParser; import org.mariadb.jdbc.internal.failover.FailoverProxy; -import org.mariadb.jdbc.internal.failover.impl.MastersSlavesListener; +import org.mariadb.jdbc.internal.failover.impl.MastersReplicasListener; import org.mariadb.jdbc.internal.failover.tools.SearchFilter; import org.mariadb.jdbc.internal.io.LruTraceCache; import org.mariadb.jdbc.internal.util.pool.GlobalStateInfo; -public class MastersSlavesProtocol extends MasterProtocol { +public class MastersReplicasProtocol extends MasterProtocol { protected boolean masterConnection = false; private boolean mustBeMasterConnection = false; - public MastersSlavesProtocol( + public MastersReplicasProtocol( final UrlParser url, final GlobalStateInfo globalInfo, final ReentrantLock lock, @@ -86,13 +86,13 @@ public MastersSlavesProtocol( * @throws SQLException if not found */ public static void loop( - MastersSlavesListener listener, + MastersReplicasListener listener, final GlobalStateInfo globalInfo, final List addresses, SearchFilter searchFilter) throws SQLException { - MastersSlavesProtocol protocol; + MastersReplicasProtocol protocol; ArrayDeque loopAddresses = new ArrayDeque<>(addresses); if (loopAddresses.isEmpty()) { resetHostList(listener, loopAddresses); @@ -147,7 +147,7 @@ public static void loop( return; } - // in case master not found but slave is , and allowing master down + // in case master not found but replica is , and allowing master down if (loopAddresses.isEmpty() && (listener.isMasterHostFailReconnect() && listener.urlParser.getOptions().allowMasterDownConnection @@ -155,14 +155,15 @@ public static void loop( return; } - // on connection and all slaves have been tested, use master if on + // on connection and all replicas have been tested, use master if on if (loopAddresses.isEmpty() && searchFilter.isInitialConnection() && !listener.isMasterHostFailReconnect()) { return; } - // if server has try to connect to all host, and there is remaining master or slave that fail + // if server has try to connect to all host, and there is remaining master or replica that + // fail // add all servers back to continue looping until maxConnectionTry is reached if (loopAddresses.isEmpty() && !searchFilter.isFailoverLoop() && maxConnectionTry > 0) { resetHostList(listener, loopAddresses); @@ -203,7 +204,7 @@ public static void loop( * @param loopAddresses the list to reinitialize */ private static void resetHostList( - MastersSlavesListener listener, Deque loopAddresses) { + MastersReplicasListener listener, Deque loopAddresses) { // if all servers have been connected without result // add back all servers List servers = new ArrayList<>(); @@ -218,7 +219,9 @@ private static void resetHostList( } protected static boolean foundMaster( - MastersSlavesListener listener, MastersSlavesProtocol protocol, SearchFilter searchFilter) { + MastersReplicasListener listener, + MastersReplicasProtocol protocol, + SearchFilter searchFilter) { protocol.setMustBeMasterConnection(true); if (listener.isMasterHostFailReconnect()) { listener.foundActiveMaster(protocol); @@ -236,7 +239,7 @@ protected static boolean foundMaster( } protected static boolean foundSecondary( - MastersSlavesListener listener, MastersSlavesProtocol protocol, SearchFilter searchFilter) + MastersReplicasListener listener, MastersReplicasProtocol protocol, SearchFilter searchFilter) throws SQLException { protocol.setMustBeMasterConnection(false); if (listener.isSecondaryHostFailReconnect()) { @@ -249,22 +252,22 @@ protected static boolean foundSecondary( return true; } else { return listener.isExplicitClosed() - || searchFilter.isFineIfFoundOnlySlave() + || searchFilter.isFineIfFoundOnlyReplica() || !listener.isMasterHostFailReconnect(); } } /** - * Get new instance of MastersSlavesProtocol. + * Get new instance of MastersReplicasProtocol. * * @param proxy proxy * @param urlParser connection string Object. - * @return a new MastersSlavesProtocol instance + * @return a new MastersReplicasProtocol instance */ - private static MastersSlavesProtocol getNewProtocol( + private static MastersReplicasProtocol getNewProtocol( FailoverProxy proxy, final GlobalStateInfo globalInfo, UrlParser urlParser) { - MastersSlavesProtocol newProtocol = - new MastersSlavesProtocol(urlParser, globalInfo, proxy.lock, proxy.traceCache); + MastersReplicasProtocol newProtocol = + new MastersReplicasProtocol(urlParser, globalInfo, proxy.lock, proxy.traceCache); newProtocol.setProxy(proxy); return newProtocol; } diff --git a/src/main/java/org/mariadb/jdbc/internal/util/Utils.java b/src/main/java/org/mariadb/jdbc/internal/util/Utils.java index 0d4102505..cbfac43aa 100644 --- a/src/main/java/org/mariadb/jdbc/internal/util/Utils.java +++ b/src/main/java/org/mariadb/jdbc/internal/util/Utils.java @@ -72,14 +72,14 @@ import org.mariadb.jdbc.internal.failover.FailoverProxy; import org.mariadb.jdbc.internal.failover.impl.AuroraListener; import org.mariadb.jdbc.internal.failover.impl.MastersFailoverListener; -import org.mariadb.jdbc.internal.failover.impl.MastersSlavesListener; +import org.mariadb.jdbc.internal.failover.impl.MastersReplicasListener; import org.mariadb.jdbc.internal.io.LruTraceCache; import org.mariadb.jdbc.internal.io.socket.SocketHandlerFunction; import org.mariadb.jdbc.internal.io.socket.SocketUtility; import org.mariadb.jdbc.internal.logging.ProtocolLoggingProxy; import org.mariadb.jdbc.internal.protocol.AuroraProtocol; import org.mariadb.jdbc.internal.protocol.MasterProtocol; -import org.mariadb.jdbc.internal.protocol.MastersSlavesProtocol; +import org.mariadb.jdbc.internal.protocol.MastersReplicasProtocol; import org.mariadb.jdbc.internal.protocol.Protocol; import org.mariadb.jdbc.internal.util.pool.GlobalStateInfo; import org.mariadb.jdbc.util.ConfigurableSocketFactory; @@ -614,10 +614,10 @@ public static Protocol retrieveProxy(final UrlParser urlParser, final GlobalStat urlParser, (Protocol) Proxy.newProxyInstance( - MastersSlavesProtocol.class.getClassLoader(), + MastersReplicasProtocol.class.getClassLoader(), new Class[] {Protocol.class}, new FailoverProxy( - new MastersSlavesListener(urlParser, globalInfo), lock, traceCache))); + new MastersReplicasListener(urlParser, globalInfo), lock, traceCache))); case LOADBALANCE: case SEQUENTIAL: return getProxyLoggingIfNeeded( diff --git a/src/main/java/org/mariadb/jdbc/internal/util/constant/ParameterConstant.java b/src/main/java/org/mariadb/jdbc/internal/util/constant/ParameterConstant.java index a43e25555..b42ea44b4 100644 --- a/src/main/java/org/mariadb/jdbc/internal/util/constant/ParameterConstant.java +++ b/src/main/java/org/mariadb/jdbc/internal/util/constant/ParameterConstant.java @@ -55,5 +55,5 @@ public class ParameterConstant { public static final String TYPE_MASTER = "master"; - public static final String TYPE_SLAVE = "slave"; + public static final String TYPE_REPLICA = "replica"; } diff --git a/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java b/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java index 7664503fb..eb283c41f 100644 --- a/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java +++ b/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java @@ -581,8 +581,8 @@ public enum DefaultOptions { "allowMasterDownConnection", Boolean.FALSE, "2.2.0", - "When using master/slave configuration, " - + "permit to create connection when master is down. If no master is up, default connection is then a slave " + "When using master/replica configuration, " + + "permit to create connection when master is down. If no master is up, default connection is then a replica " + "and Connection.isReadOnly() will then return true.", false), GALERA_ALLOWED_STATE( diff --git a/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java b/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java index 38d20126a..21c824578 100644 --- a/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java +++ b/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java @@ -55,7 +55,6 @@ import static org.junit.Assert.*; import java.sql.*; - import org.junit.Assume; import org.junit.Test; import org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory; diff --git a/src/test/java/org/mariadb/jdbc/ConnectionTest.java b/src/test/java/org/mariadb/jdbc/ConnectionTest.java index 140f2e005..ae96348c2 100644 --- a/src/test/java/org/mariadb/jdbc/ConnectionTest.java +++ b/src/test/java/org/mariadb/jdbc/ConnectionTest.java @@ -676,7 +676,7 @@ private void checkConnection(String conUrl, int min, int max) { } @Test - public void slaveDownConnection() throws SQLException { + public void replicaDownConnection() throws SQLException { Assume.assumeTrue(System.getenv("SKYSQL") == null); String url = "jdbc:mariadb:replication://" diff --git a/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java b/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java index 3664cc5a7..2422cbe57 100644 --- a/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java +++ b/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java @@ -171,7 +171,7 @@ public void interruptExecuteBatch() throws Exception { @Test public void serverBulk1mTest() throws SQLException { Assume.assumeTrue(checkMaxAllowedPacketMore8m("serverBulk1mTest")); - Assume.assumeTrue(runLongTest); + // Assume.assumeTrue(runLongTest); Assume.assumeFalse(sharedIsAurora()); Assume.assumeTrue(isMariadbServer()); diff --git a/src/test/java/org/mariadb/jdbc/JdbcParserTest.java b/src/test/java/org/mariadb/jdbc/JdbcParserTest.java index f669b918b..53a0fb9a0 100644 --- a/src/test/java/org/mariadb/jdbc/JdbcParserTest.java +++ b/src/test/java/org/mariadb/jdbc/JdbcParserTest.java @@ -181,11 +181,11 @@ public void testUrl() throws SQLException { "DB", Arrays.asList( new HostAddress("host1", 3306), - new HostAddress("host2", 3307, ParameterConstant.TYPE_SLAVE)), + new HostAddress("host2", 3307, ParameterConstant.TYPE_REPLICA)), new Options(), HaMode.REPLICATION); assertEquals( - "jdbc:mariadb:replication://address=(host=host1)(port=3306)(type=master),address=(host=host2)(port=3307)(type=slave)/DB", + "jdbc:mariadb:replication://address=(host=host1)(port=3306)(type=master),address=(host=host2)(port=3307)(type=replica)/DB", parser.getInitialUrl()); parser.setDatabase("DB2"); assertEquals("DB2", parser.getDatabase()); @@ -352,7 +352,7 @@ public void testOptionParseIntegerNotPossible() throws Throwable { @Test() public void testJdbcParserSimpleIpv4basic() throws SQLException { - String url = "jdbc:mariadb://master:3306,slave1:3307,slave2:3308/database"; + String url = "jdbc:mariadb://master:3306,replica1:3307,replica2:3308/database"; UrlParser.parse(url); } @@ -364,20 +364,20 @@ public void testJdbcParserSimpleIpv4basicError() throws SQLException { @Test public void testJdbcParserSimpleIpv4basicwithoutDatabase() throws SQLException { - String url = "jdbc:mariadb://master:3306,slave1:3307,slave2:3308/"; + String url = "jdbc:mariadb://master:3306,replica1:3307,replica2:3308/"; UrlParser urlParser = UrlParser.parse(url); assertNull(urlParser.getDatabase()); assertNull(urlParser.getUsername()); assertNull(urlParser.getPassword()); assertTrue(urlParser.getHostAddresses().size() == 3); assertTrue(new HostAddress("master", 3306).equals(urlParser.getHostAddresses().get(0))); - assertTrue(new HostAddress("slave1", 3307).equals(urlParser.getHostAddresses().get(1))); - assertTrue(new HostAddress("slave2", 3308).equals(urlParser.getHostAddresses().get(2))); + assertTrue(new HostAddress("replica1", 3307).equals(urlParser.getHostAddresses().get(1))); + assertTrue(new HostAddress("replica2", 3308).equals(urlParser.getHostAddresses().get(2))); } @Test public void testJdbcParserWithoutDatabaseWithProperties() throws SQLException { - String url = "jdbc:mariadb://master:3306,slave1:3307,slave2:3308?autoReconnect=true"; + String url = "jdbc:mariadb://master:3306,replica1:3307,replica2:3308?autoReconnect=true"; UrlParser urlParser = UrlParser.parse(url); assertNull(urlParser.getDatabase()); assertNull(urlParser.getUsername()); @@ -385,13 +385,14 @@ public void testJdbcParserWithoutDatabaseWithProperties() throws SQLException { assertTrue(urlParser.getOptions().autoReconnect); assertTrue(urlParser.getHostAddresses().size() == 3); assertTrue(new HostAddress("master", 3306).equals(urlParser.getHostAddresses().get(0))); - assertTrue(new HostAddress("slave1", 3307).equals(urlParser.getHostAddresses().get(1))); - assertTrue(new HostAddress("slave2", 3308).equals(urlParser.getHostAddresses().get(2))); + assertTrue(new HostAddress("replica1", 3307).equals(urlParser.getHostAddresses().get(1))); + assertTrue(new HostAddress("replica2", 3308).equals(urlParser.getHostAddresses().get(2))); } @Test public void testJdbcParserSimpleIpv4Properties() throws SQLException { - String url = "jdbc:mariadb://master:3306,slave1:3307,slave2:3308/database?autoReconnect=true"; + String url = + "jdbc:mariadb://master:3306,replica1:3307,replica2:3308/database?autoReconnect=true"; Properties prop = new Properties(); prop.setProperty("user", "greg"); prop.setProperty("password", "pass"); @@ -403,13 +404,13 @@ public void testJdbcParserSimpleIpv4Properties() throws SQLException { assertTrue(urlParser.getOptions().autoReconnect); assertTrue(urlParser.getHostAddresses().size() == 3); assertTrue(new HostAddress("master", 3306).equals(urlParser.getHostAddresses().get(0))); - assertTrue(new HostAddress("slave1", 3307).equals(urlParser.getHostAddresses().get(1))); - assertTrue(new HostAddress("slave2", 3308).equals(urlParser.getHostAddresses().get(2))); + assertTrue(new HostAddress("replica1", 3307).equals(urlParser.getHostAddresses().get(1))); + assertTrue(new HostAddress("replica2", 3308).equals(urlParser.getHostAddresses().get(2))); } @Test public void testJdbcParserBooleanOption() { - String url = "jdbc:mariadb://master:3306,slave1:3307,slave2:3308?autoReconnect=truee"; + String url = "jdbc:mariadb://master:3306,replica1:3307,replica2:3308?autoReconnect=truee"; Properties prop = new Properties(); prop.setProperty("user", "greg"); prop.setProperty("password", "pass"); @@ -426,15 +427,15 @@ public void testJdbcParserBooleanOption() { @Test public void testJdbcParserSimpleIpv4() throws SQLException { String url = - "jdbc:mariadb://master:3306,slave1:3307,slave2:3308/database?user=greg&password=pass"; + "jdbc:mariadb://master:3306,replica1:3307,replica2:3308/database?user=greg&password=pass"; UrlParser urlParser = UrlParser.parse(url); assertTrue("database".equals(urlParser.getDatabase())); assertTrue("greg".equals(urlParser.getUsername())); assertTrue("pass".equals(urlParser.getPassword())); assertTrue(urlParser.getHostAddresses().size() == 3); assertTrue(new HostAddress("master", 3306).equals(urlParser.getHostAddresses().get(0))); - assertTrue(new HostAddress("slave1", 3307).equals(urlParser.getHostAddresses().get(1))); - assertTrue(new HostAddress("slave2", 3308).equals(urlParser.getHostAddresses().get(2))); + assertTrue(new HostAddress("replica1", 3307).equals(urlParser.getHostAddresses().get(1))); + assertTrue(new HostAddress("replica2", 3308).equals(urlParser.getHostAddresses().get(2))); } @Test @@ -459,7 +460,7 @@ public void testJdbcParserSimpleIpv6() throws SQLException { public void testJdbcParserParameter() throws SQLException { String url = "jdbc:mariadb://address=(type=master)(port=3306)(host=master1),address=(port=3307)(type=master)" - + "(host=master2),address=(type=slave)(host=slave1)(port=3308)/database?user=greg&password=pass"; + + "(host=master2),address=(type=replica)(host=replica1)(port=3308)/database?user=greg&password=pass"; UrlParser urlParser = UrlParser.parse(url); assertTrue("database".equals(urlParser.getDatabase())); assertTrue("greg".equals(urlParser.getUsername())); @@ -470,14 +471,19 @@ public void testJdbcParserParameter() throws SQLException { assertTrue( new HostAddress("master2", 3307, "master").equals(urlParser.getHostAddresses().get(1))); assertTrue( - new HostAddress("slave1", 3308, "slave").equals(urlParser.getHostAddresses().get(2))); + new HostAddress("replica1", 3308, "replica").equals(urlParser.getHostAddresses().get(2))); + url = + "jdbc:mariadb://address=(type=master)(port=3306)(host=master1),address=(port=3307)(type=master)" + + "(host=master2),address=(type=slave)(host=replica1)(port=3308)/database?user=greg&password=pass"; + assertTrue( + new HostAddress("replica1", 3308, "replica").equals(urlParser.getHostAddresses().get(2))); } @Test(expected = SQLException.class) public void testJdbcParserParameterErrorEqual() throws SQLException { String url = "jdbc:mariadb://address=(type=)(port=3306)(host=master1),address=(port=3307)(type=master)" - + "(host=master2),address=(type=slave)(host=slave1)(port=3308)/database?user=greg&password=pass"; + + "(host=master2),address=(type=replica)(host=replica1)(port=3308)/database?user=greg&password=pass"; UrlParser.parse(url); fail("Must have throw an SQLException"); } @@ -500,7 +506,7 @@ public void testJdbcParserHaModeLoadReplication() throws SQLException { public void testJdbcParserReplicationParameter() throws SQLException { String url = "jdbc:mariadb:replication://address=(type=master)(port=3306)(host=master1),address=(port=3307)" - + "(type=master)(host=master2),address=(type=slave)(host=slave1)(port=3308)/database" + + "(type=master)(host=master2),address=(type=replica)(host=replica1)(port=3308)/database" + "?user=greg&password=pass"; UrlParser urlParser = UrlParser.parse(url); assertTrue("database".equals(urlParser.getDatabase())); @@ -512,21 +518,21 @@ public void testJdbcParserReplicationParameter() throws SQLException { assertTrue( new HostAddress("master2", 3307, "master").equals(urlParser.getHostAddresses().get(1))); assertTrue( - new HostAddress("slave1", 3308, "slave").equals(urlParser.getHostAddresses().get(2))); + new HostAddress("replica1", 3308, "replica").equals(urlParser.getHostAddresses().get(2))); } @Test public void testJdbcParserReplicationParameterWithoutType() throws SQLException { - String url = "jdbc:mariadb:replication://master1,slave1,slave2/database"; + String url = "jdbc:mariadb:replication://master1,replica1,replica2/database"; UrlParser urlParser = UrlParser.parse(url); assertTrue("database".equals(urlParser.getDatabase())); assertTrue(urlParser.getHostAddresses().size() == 3); assertTrue( new HostAddress("master1", 3306, "master").equals(urlParser.getHostAddresses().get(0))); assertTrue( - new HostAddress("slave1", 3306, "slave").equals(urlParser.getHostAddresses().get(1))); + new HostAddress("replica1", 3306, "replica").equals(urlParser.getHostAddresses().get(1))); assertTrue( - new HostAddress("slave2", 3306, "slave").equals(urlParser.getHostAddresses().get(2))); + new HostAddress("replica2", 3306, "replica").equals(urlParser.getHostAddresses().get(2))); } @Test diff --git a/src/test/java/org/mariadb/jdbc/failover/AuroraFailoverTest.java b/src/test/java/org/mariadb/jdbc/failover/AuroraFailoverTest.java index aa8348eb9..97bd345d6 100644 --- a/src/test/java/org/mariadb/jdbc/failover/AuroraFailoverTest.java +++ b/src/test/java/org/mariadb/jdbc/failover/AuroraFailoverTest.java @@ -101,7 +101,7 @@ public void testErrorWriteOnReplica() throws SQLException { try { stmt.execute("drop table if exists auroraDelete" + jobId); System.out.println( - "ERROR - > must not be able to write on slave. check if you database is start with --read-only"); + "ERROR - > must not be able to write on replica. check if you database is start with --read-only"); fail(); } catch (SQLException e) { // normal exception @@ -115,20 +115,20 @@ public void testErrorWriteOnReplica() throws SQLException { public void testReplication() throws SQLException, InterruptedException { try (Connection connection = getNewConnection(false)) { Statement stmt = connection.createStatement(); - stmt.execute("drop table if exists auroraReadSlave" + jobId); + stmt.execute("drop table if exists auroraReadReplica" + jobId); stmt.execute( - "create table auroraReadSlave" + "create table auroraReadReplica" + jobId + " (id int not null primary key auto_increment, test VARCHAR(10))"); - // wait to be sure slave have replicate data + // wait to be sure replica have replicate data Thread.sleep(1500); connection.setReadOnly(true); - ResultSet rs = stmt.executeQuery("Select count(*) from auroraReadSlave" + jobId); + ResultSet rs = stmt.executeQuery("Select count(*) from auroraReadReplica" + jobId); assertTrue(rs.next()); connection.setReadOnly(false); - stmt.execute("drop table if exists auroraReadSlave" + jobId); + stmt.execute("drop table if exists auroraReadReplica" + jobId); } } @@ -240,7 +240,7 @@ public void testClearBlacklist() throws Throwable { Statement st = connection.createStatement(); try { st.execute("SELECT 1 "); - // switch connection to master -> slave blacklisted + // switch connection to master -> replica blacklisted } catch (SQLException e) { fail("must not have been here"); } diff --git a/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java b/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java index 58593c4a4..ab55a3eb8 100644 --- a/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java +++ b/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java @@ -65,7 +65,7 @@ public abstract class BaseReplication extends BaseMonoServer { @Test - public void failoverSlaveToMasterPrepareStatement() throws Throwable { + public void failoverReplicaToMasterPrepareStatement() throws Throwable { try (Connection connection = getNewConnection( "&retriesAllDown=6&connectTimeout=1000&socketTimeout=1000" @@ -80,22 +80,22 @@ public void failoverSlaveToMasterPrepareStatement() throws Throwable { stmt.execute("insert into replicationFailoverBinary" + jobId + "(test) values ('Harriba !')"); final int masterServerId = getServerId(connection); connection.setReadOnly(true); - // wait for table replication on slave + // wait for table replication on replica Thread.sleep(200); // create another prepareStatement, to permit to verify that prepare id has changed connection.prepareStatement("SELECT ?"); - // prepareStatement on slave connection + // prepareStatement on replica connection PreparedStatement preparedStatement = connection.prepareStatement( "SELECT test from replicationFailoverBinary" + jobId + " where id = ?"); final long currentPrepareId = getPrepareResult((ServerSidePreparedStatement) preparedStatement).getStatementId(); - int slaveServerId = getServerId(connection); - assertFalse(masterServerId == slaveServerId); - // stop slave for a few seconds - stopProxy(slaveServerId, 2000); + int replicaServerId = getServerId(connection); + assertFalse(masterServerId == replicaServerId); + // stop replica for a few seconds + stopProxy(replicaServerId, 2000); // test failover preparedStatement.setInt(1, 1); @@ -111,7 +111,7 @@ public void failoverSlaveToMasterPrepareStatement() throws Throwable { assertTrue(masterServerId == currentServerId); assertFalse(connection.isReadOnly()); Thread.sleep(2000); - boolean hasReturnOnSlave = false; + boolean hasReturnOnReplica = false; for (int i = 0; i < 10; i++) { Thread.sleep(1000); @@ -122,38 +122,38 @@ public void failoverSlaveToMasterPrepareStatement() throws Throwable { currentServerId = getServerId(connection); if (currentServerId != masterServerId) { - hasReturnOnSlave = true; + hasReturnOnReplica = true; assertTrue(connection.isReadOnly()); break; } } - assertTrue("Prepare statement has not return on Slave", hasReturnOnSlave); + assertTrue("Prepare statement has not return on Replica", hasReturnOnReplica); } } @Test() - public void failoverSlaveAndMasterRewrite() throws Throwable { + public void failoverReplicaAndMasterRewrite() throws Throwable { try (Connection connection = getNewConnection( "&rewriteBatchedStatements=true&retriesAllDown=6&connectTimeout=2000&socketTimeout=2000", true)) { int masterServerId = getServerId(connection); connection.setReadOnly(true); - int firstSlaveId = getServerId(connection); + int firstReplicaId = getServerId(connection); stopProxy(masterServerId); // stop proxy for 2s - stopProxy(firstSlaveId, 4000); + stopProxy(firstReplicaId, 4000); try { Statement stmt = connection.createStatement(); stmt.addBatch("DO 1"); stmt.addBatch("DO 2"); int[] resultData = stmt.executeBatch(); - int secondSlaveId = getServerId(connection); + int secondReplicaId = getServerId(connection); assertEquals( "the 2 batch queries must have been executed when failover", 2, resultData.length); - assertTrue(secondSlaveId != firstSlaveId && secondSlaveId != masterServerId); + assertTrue(secondReplicaId != firstReplicaId && secondReplicaId != masterServerId); } catch (SQLException e) { e.printStackTrace(); fail(); @@ -162,14 +162,14 @@ public void failoverSlaveAndMasterRewrite() throws Throwable { } @Test - public void failoverSlaveToMaster() throws Throwable { + public void failoverReplicaToMaster() throws Throwable { try (Connection connection = getNewConnection("&retriesAllDown=6&connectTimeout=1000&socketTimeout=1000", true)) { int masterServerId = getServerId(connection); connection.setReadOnly(true); - int slaveServerId = getServerId(connection); - assertFalse(masterServerId == slaveServerId); - stopProxy(slaveServerId); + int replicaServerId = getServerId(connection); + assertFalse(masterServerId == replicaServerId); + stopProxy(replicaServerId); connection.createStatement().execute("SELECT 1"); int currentServerId = getServerId(connection); @@ -179,34 +179,34 @@ public void failoverSlaveToMaster() throws Throwable { } @Test - public void failoverDuringSlaveSetReadOnly() throws Throwable { + public void failoverDuringReplicaSetReadOnly() throws Throwable { try (Connection connection = getNewConnection("&socketTimeout=3000", true)) { connection.setReadOnly(true); - int slaveServerId = getServerId(connection); + int replicaServerId = getServerId(connection); - stopProxy(slaveServerId, 2000); + stopProxy(replicaServerId, 2000); connection.setReadOnly(false); int masterServerId = getServerId(connection); - assertFalse(slaveServerId == masterServerId); + assertFalse(replicaServerId == masterServerId); assertFalse(connection.isReadOnly()); } Thread.sleep(2500); // for not interfering with other tests } @Test() - public void failoverSlaveAndMasterWithoutAutoConnect() throws Throwable { + public void failoverReplicaAndMasterWithoutAutoConnect() throws Throwable { try (Connection connection = getNewConnection("&retriesAllDown=20&connectTimeout=2000&socketTimeout=2000", true)) { int masterServerId = getServerId(connection); connection.setReadOnly(true); - int firstSlaveId = getServerId(connection); + int firstReplicaId = getServerId(connection); stopProxy(masterServerId); - stopProxy(firstSlaveId); + stopProxy(firstReplicaId); try { - // will connect to second slave that isn't stopped + // will connect to second replica that isn't stopped connection.createStatement().executeQuery("SELECT CONNECTION_ID()"); } catch (SQLException e) { e.printStackTrace(); @@ -216,25 +216,25 @@ public void failoverSlaveAndMasterWithoutAutoConnect() throws Throwable { } @Test - public void reconnectSlaveAndMasterWithAutoConnect() throws Throwable { + public void reconnectReplicaAndMasterWithAutoConnect() throws Throwable { try (Connection connection = getNewConnection("&retriesAllDown=6&connectTimeout=2000&socketTimeout=2000", true)) { - // search actual server_id for master and slave + // search actual server_id for master and replica int masterServerId = getServerId(connection); connection.setReadOnly(true); - int firstSlaveId = getServerId(connection); + int firstReplicaId = getServerId(connection); stopProxy(masterServerId); - stopProxy(firstSlaveId); + stopProxy(firstReplicaId); - // must reconnect to the second slave without error + // must reconnect to the second replica without error connection.createStatement().execute("SELECT 1"); - int currentSlaveId = getServerId(connection); - assertTrue(currentSlaveId != firstSlaveId); - assertTrue(currentSlaveId != masterServerId); + int currentReplicaId = getServerId(connection); + assertTrue(currentReplicaId != firstReplicaId); + assertTrue(currentReplicaId != masterServerId); } } @@ -255,30 +255,30 @@ public void failoverMasterWithAutoConnect() throws Throwable { } @Test - public void writeToSlaveAfterFailover() throws Throwable { + public void writeToReplicaAfterFailover() throws Throwable { try (Connection connection = getNewConnection("&retriesAllDown=6&connectTimeout=1000&socketTimeout=1000", true)) { - // if super user can write on slave - Assume.assumeTrue(!hasSuperPrivilege(connection, "writeToSlaveAfterFailover")); + // if super user can write on replica + Assume.assumeTrue(!hasSuperPrivilege(connection, "writeToReplicaAfterFailover")); Statement st = connection.createStatement(); - st.execute("drop table if exists writeToSlave" + jobId); + st.execute("drop table if exists writeToReplica" + jobId); st.execute( - "create table writeToSlave" + "create table writeToReplica" + jobId + " (id int not null primary key , amount int not null) ENGINE = InnoDB"); - st.execute("insert into writeToSlave" + jobId + " (id, amount) VALUE (1 , 100)"); + st.execute("insert into writeToReplica" + jobId + " (id, amount) VALUE (1 , 100)"); int masterServerId = getServerId(connection); stopProxy(masterServerId); try { - st.execute("insert into writeToSlave" + jobId + " (id, amount) VALUE (2 , 100)"); + st.execute("insert into writeToReplica" + jobId + " (id, amount) VALUE (2 , 100)"); fail(); } catch (SQLException e) { // normal exception restartProxy(masterServerId); st = connection.createStatement(); - st.execute("drop table if exists writeToSlave" + jobId); + st.execute("drop table if exists writeToReplica" + jobId); } } } @@ -318,7 +318,7 @@ public void closeWhenInReconnectionLoop() throws Throwable { getNewConnection("&connectTimeout=1000&socketTimeout=1000", true)) { int masterId = getServerId(connection); connection.setReadOnly(true); - // close all slave proxy + // close all replica proxy stopProxyButParameter(masterId); // trigger the failover, so a failover thread is launched @@ -331,14 +331,14 @@ public void closeWhenInReconnectionLoop() throws Throwable { } @Test - public void failoverSlaveToMasterFail() throws Throwable { + public void failoverReplicaToMasterFail() throws Throwable { try (Connection connection = getNewConnection("&connectTimeout=1000&socketTimeout=1000&retriesAllDown=6", true)) { int masterServerId = getServerId(connection); connection.setReadOnly(true); - int slaveServerId = getServerId(connection); - assertTrue(slaveServerId != masterServerId); + int replicaServerId = getServerId(connection); + assertTrue(replicaServerId != masterServerId); connection.setCatalog( "mysql"); // to be sure there will be a query, and so an error when switching connection @@ -364,9 +364,9 @@ public void failoverDuringMasterSetReadOnly() throws Throwable { connection.setReadOnly(true); - int slaveServerId = getServerId(connection); + int replicaServerId = getServerId(connection); - assertFalse(slaveServerId == masterServerId); + assertFalse(replicaServerId == masterServerId); assertTrue(connection.isReadOnly()); restartProxy(masterServerId); } diff --git a/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java b/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java index e4937b967..e7bccad19 100644 --- a/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java +++ b/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java @@ -153,8 +153,8 @@ public void failoverDuringMasterSetReadOnly() throws Throwable { int masterServerId = getServerId(connection); stopProxy(masterServerId); connection.setReadOnly(true); - int slaveServerId = getServerId(connection); - assertFalse(slaveServerId == masterServerId); + int replicaServerId = getServerId(connection); + assertFalse(replicaServerId == masterServerId); assertTrue(connection.isReadOnly()); } } @@ -165,11 +165,11 @@ public void masterWithoutFailover() throws Throwable { getNewConnection("&retriesAllDown=6&connectTimeout=1000&socketTimeout=1000", true)) { int masterServerId = getServerId(connection); connection.setReadOnly(true); - int firstSlaveId = getServerId(connection); + int firstReplicaId = getServerId(connection); connection.setReadOnly(false); stopProxy(masterServerId); - stopProxy(firstSlaveId); + stopProxy(firstReplicaId); connection.createStatement().executeQuery("SELECT CONNECTION_ID()"); fail(); @@ -177,7 +177,7 @@ public void masterWithoutFailover() throws Throwable { } @Test - public void checkBackOnMasterOnSlaveFail() throws Throwable { + public void checkBackOnMasterOnReplicaFail() throws Throwable { try (Connection connection = getNewConnection( "&retriesAllDown=6&failOnReadOnly=true&connectTimeout=1000&socketTimeout=1000", true)) { @@ -212,7 +212,7 @@ public void checkBackOnMasterOnSlaveFail() throws Throwable { } @Test - public void testFailNotOnSlave() throws Throwable { + public void testFailNotOnReplica() throws Throwable { try (Connection connection = getNewConnection("&retriesAllDown=6&connectTimeout=1000&socketTimeout=1000", true)) { Statement stmt = connection.createStatement(); @@ -229,7 +229,7 @@ public void testFailNotOnSlave() throws Throwable { } @Test - public void commitExecutionOnSlave() throws SQLException { + public void commitExecutionOnReplica() throws SQLException { try (Connection conn = getNewConnection()) { Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE IF NOT EXISTS commitExecution(id int, val varchar(256))"); From 090d921a1bd45510b5a4e9b567648de67fa47cf5 Mon Sep 17 00:00:00 2001 From: rusher Date: Wed, 18 Nov 2020 18:06:55 +0100 Subject: [PATCH 22/25] [misc] correct prepare cache statement ensuring reusing cache. additionnal : pipelining batch cannot have a non prepare statement, so simplification --- .../internal/com/send/ComStmtPrepare.java | 6 +- .../internal/protocol/AbstractMultiSend.java | 77 +++---------------- .../protocol/AbstractQueryProtocol.java | 18 ++--- .../internal/protocol/AsyncMultiRead.java | 18 ----- .../jdbc/internal/protocol/Protocol.java | 2 +- .../util/ServerPrepareStatementCache.java | 5 ++ .../util/dao/ServerPrepareResult.java | 9 +-- .../org/mariadb/jdbc/AutoReconnectTest.java | 1 + 8 files changed, 32 insertions(+), 104 deletions(-) diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java b/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java index 3e9e5f48f..3575f5318 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java @@ -80,11 +80,12 @@ public ComStmtPrepare(Protocol protocol, String sql) { * @param pos the writer * @throws IOException if connection error occur */ - public void send(PacketOutputStream pos) throws IOException { + public ComStmtPrepare send(PacketOutputStream pos) throws IOException { pos.startPacket(0); pos.write(COM_STMT_PREPARE); pos.write(this.sql); pos.flush(); + return this; } /** @@ -156,7 +157,8 @@ public ServerPrepareResult read(PacketInputStream reader, boolean eofDeprecated) && sql.length() < protocol.getOptions().prepStmtCacheSqlLimit) { String key = protocol.getDatabase() + "-" + sql; ServerPrepareResult cachedServerPrepareResult = - protocol.addPrepareInCache(key, serverPrepareResult); + protocol.putInCache(key, serverPrepareResult); + // if same prepare result is already cached, dismissed prepared result, and reuse cached entry return cachedServerPrepareResult != null ? cachedServerPrepareResult : serverPrepareResult; } return serverPrepareResult; diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java index 376d3e29c..032255b2e 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java @@ -78,7 +78,6 @@ public abstract class AbstractMultiSend { private final PacketOutputStream writer; private final Results results; private final boolean binaryProtocol; - private final boolean readPrepareStmtResult; protected int statementId = -1; protected ColumnType[] parameterTypeHeader; private List parametersList; @@ -95,7 +94,6 @@ public abstract class AbstractMultiSend { * @param results query results * @param serverPrepareResult Prepare result * @param parametersList parameters - * @param readPrepareStmtResult must execute prepare result * @param sql sql query. * @param readScheduler reading thread-pool */ @@ -105,7 +103,6 @@ public AbstractMultiSend( Results results, ServerPrepareResult serverPrepareResult, List parametersList, - boolean readPrepareStmtResult, String sql, ThreadPoolExecutor readScheduler) { this.protocol = protocol; @@ -114,7 +111,6 @@ public AbstractMultiSend( this.prepareResult = serverPrepareResult; this.parametersList = parametersList; this.binaryProtocol = true; - this.readPrepareStmtResult = readPrepareStmtResult; this.sql = sql; this.readScheduler = readScheduler; } @@ -142,7 +138,6 @@ public AbstractMultiSend( this.prepareResult = clientPrepareResult; this.parametersList = parametersList; this.binaryProtocol = false; - this.readPrepareStmtResult = false; this.readScheduler = readScheduler; } @@ -166,7 +161,6 @@ public AbstractMultiSend( this.results = results; this.queries = queries; this.binaryProtocol = false; - this.readPrepareStmtResult = false; this.readScheduler = readScheduler; } @@ -202,32 +196,15 @@ public PrepareResult getPrepareResult() { * Execute Bulk execution (send packets by batch of useBatchMultiSendNumber or when max packet is * reached) before reading results. * - * @return prepare result * @throws SQLException if any error occur */ - public PrepareResult executeBatch() throws SQLException { + public void executeBatch() throws SQLException { int paramCount = getParamCount(); if (binaryProtocol) { - if (readPrepareStmtResult) { - parameterTypeHeader = new ColumnType[paramCount]; - if (prepareResult == null - && protocol.getOptions().cachePrepStmts - && protocol.getOptions().useServerPrepStmts) { - String key = protocol.getDatabase() + "-" + sql; - prepareResult = protocol.prepareStatementCache().get(key); - if (prepareResult != null - && !((ServerPrepareResult) prepareResult).incrementShareCounter()) { - // in cache but been de-allocated - prepareResult = null; - } - } - statementId = - (prepareResult == null) ? -1 : ((ServerPrepareResult) prepareResult).getStatementId(); - } else if (prepareResult != null) { - statementId = ((ServerPrepareResult) prepareResult).getStatementId(); - } + parameterTypeHeader = new ColumnType[paramCount]; + statementId = ((ServerPrepareResult) prepareResult).getStatementId(); } - return executeBatchStandard(paramCount); + executeBatchStandard(paramCount); } /** @@ -235,15 +212,13 @@ public PrepareResult executeBatch() throws SQLException { * reached) before reading results. * * @param estimatedParameterCount parameter counter - * @return prepare result * @throws SQLException if any error occur */ - private PrepareResult executeBatchStandard(int estimatedParameterCount) throws SQLException { + private void executeBatchStandard(int estimatedParameterCount) throws SQLException { int totalExecutionNumber = getTotalExecutionNumber(); SQLException exception = null; BulkStatus status = new BulkStatus(); - ComStmtPrepare comStmtPrepare = null; FutureTask futureReadTask = null; int requestNumberByBulk; @@ -258,18 +233,6 @@ private PrepareResult executeBatchStandard(int estimatedParameterCount) throws S protocol.getOptions().useBatchMultiSendNumber); protocol.changeSocketTcpNoDelay(false); // enable NAGLE algorithm temporary. - // add prepare sub-command - if (readPrepareStmtResult && prepareResult == null) { - - comStmtPrepare = new ComStmtPrepare(protocol, sql); - comStmtPrepare.send(writer); - - // read prepare result - prepareResult = comStmtPrepare.read(protocol.getReader(), protocol.isEofDeprecated()); - statementId = ((ServerPrepareResult) prepareResult).getStatementId(); - paramCount = getParamCount(); - } - boolean useCurrentThread = false; for (; status.sendSubCmdCounter < requestNumberByBulk; ) { @@ -280,11 +243,10 @@ private PrepareResult executeBatchStandard(int estimatedParameterCount) throws S try { protocol.getResult(results); } catch (SQLException qex) { - if (((readPrepareStmtResult && prepareResult == null) - || !protocol.getOptions().continueBatchOnError)) { + if (!protocol.getOptions().continueBatchOnError) { throw qex; } else { - exception = qex; + if (exception == null) exception = qex; } } } else if (futureReadTask == null) { @@ -292,10 +254,8 @@ private PrepareResult executeBatchStandard(int estimatedParameterCount) throws S futureReadTask = new FutureTask<>( new AsyncMultiRead( - comStmtPrepare, status, protocol, - false, this, paramCount, results, @@ -308,11 +268,10 @@ private PrepareResult executeBatchStandard(int estimatedParameterCount) throws S try { protocol.getResult(results); } catch (SQLException qex) { - if (((readPrepareStmtResult && prepareResult == null) - || !protocol.getOptions().continueBatchOnError)) { + if (!protocol.getOptions().continueBatchOnError) { throw qex; } else { - exception = qex; + if (exception == null) exception = qex; } } } @@ -324,22 +283,8 @@ private PrepareResult executeBatchStandard(int estimatedParameterCount) throws S protocol.changeSocketTcpNoDelay(protocol.getOptions().tcpNoDelay); try { AsyncMultiReadResult asyncMultiReadResult = futureReadTask.get(); - - if (binaryProtocol - && prepareResult == null - && asyncMultiReadResult.getPrepareResult() != null) { - prepareResult = asyncMultiReadResult.getPrepareResult(); - statementId = ((ServerPrepareResult) prepareResult).getStatementId(); - paramCount = prepareResult.getParamCount(); - } - if (asyncMultiReadResult.getException() != null) { - if (((readPrepareStmtResult && prepareResult == null) - || !protocol.getOptions().continueBatchOnError)) { - throw asyncMultiReadResult.getException(); - } else { - exception = asyncMultiReadResult.getException(); - } + if (exception == null) exception = asyncMultiReadResult.getException(); } } catch (ExecutionException executionException) { if (executionException.getCause() == null) { @@ -375,8 +320,6 @@ private PrepareResult executeBatchStandard(int estimatedParameterCount) throws S throw exception; } - return prepareResult; - } catch (IOException e) { status.sendEnded = true; status.sendCmdCounter = 0; // to ensure read doesn't hang diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java index f86f6c6e6..1d109c385 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java @@ -869,13 +869,11 @@ public ServerPrepareResult prepare(String sql, boolean executeOnMaster) throws S } cmdPrologue(); - writer.startPacket(0); - writer.write(COM_STMT_PREPARE); - writer.write(sql); - writer.flush(); - ComStmtPrepare comStmtPrepare = new ComStmtPrepare(this, sql); - return comStmtPrepare.read(reader, eofDeprecated); + return new ComStmtPrepare(this, sql) + .send(writer) + .read(reader, eofDeprecated); + } catch (IOException e) { throw exceptionWithQuery(sql, handleIoException(e), explicitClosed); } finally { @@ -1020,7 +1018,7 @@ && executeBulkBatch(results, sql, serverPrepareResult, parametersList)) { } initializeBatchReader(); new AbstractMultiSend( - this, writer, results, serverPrepareResult, parametersList, true, sql, readScheduler) { + this, writer, results, serverPrepareResult, parametersList, sql, readScheduler) { @Override public void sendCmd( PacketOutputStream writer, @@ -1078,9 +1076,7 @@ public SQLException handleResultException( @Override public int getParamCount() { - return getPrepareResult() == null - ? parametersList.get(0).length - : ((ServerPrepareResult) getPrepareResult()).getParameters().length; + return serverPrepareResult.getParameters().length; } @Override @@ -1902,7 +1898,7 @@ public void prolog( connection.reenableWarnings(); } - public ServerPrepareResult addPrepareInCache( + public ServerPrepareResult putInCache( String key, ServerPrepareResult serverPrepareResult) { return serverPrepareStatementCache.put(key, serverPrepareResult); } diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AsyncMultiRead.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AsyncMultiRead.java index ae61d6026..af602b63f 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AsyncMultiRead.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AsyncMultiRead.java @@ -60,18 +60,15 @@ import java.util.List; import java.util.concurrent.Callable; import org.mariadb.jdbc.internal.com.read.dao.Results; -import org.mariadb.jdbc.internal.com.send.ComStmtPrepare; import org.mariadb.jdbc.internal.com.send.parameters.ParameterHolder; import org.mariadb.jdbc.internal.util.BulkStatus; import org.mariadb.jdbc.internal.util.dao.PrepareResult; public class AsyncMultiRead implements Callable { - private final ComStmtPrepare comStmtPrepare; private final BulkStatus status; private final int sendCmdInitialCounter; private final Protocol protocol; - private final boolean readPrepareStmtResult; private final AbstractMultiSend bulkSend; private final List parametersList; private final List queries; @@ -82,10 +79,8 @@ public class AsyncMultiRead implements Callable { /** * Read results async to avoid local and remote networking stack buffer overflow "lock". * - * @param comStmtPrepare current prepare * @param status bulk status * @param protocol protocol - * @param readPrepareStmtResult must read prepare statement result * @param bulkSend bulk sender object * @param paramCount number of parameters * @param results execution result @@ -94,21 +89,17 @@ public class AsyncMultiRead implements Callable { * @param prepareResult prepare result */ public AsyncMultiRead( - ComStmtPrepare comStmtPrepare, BulkStatus status, Protocol protocol, - boolean readPrepareStmtResult, AbstractMultiSend bulkSend, int paramCount, Results results, List parametersList, List queries, PrepareResult prepareResult) { - this.comStmtPrepare = comStmtPrepare; this.status = status; this.sendCmdInitialCounter = status.sendCmdCounter - 1; this.protocol = protocol; - this.readPrepareStmtResult = readPrepareStmtResult; this.bulkSend = bulkSend; this.paramCount = paramCount; this.results = results; @@ -129,15 +120,6 @@ public AsyncMultiReadResult call() throws Exception { protocol.changeSocketSoTimeout(0); } - if (readPrepareStmtResult) { - try { - asyncMultiReadResult.setPrepareResult( - comStmtPrepare.read(protocol.getReader(), protocol.isEofDeprecated())); - } catch (SQLException queryException) { - asyncMultiReadResult.setException(queryException); - } - } - // read all corresponding results int counter = 0; diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java index f3ea6ac9e..779503d0f 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/Protocol.java @@ -273,7 +273,7 @@ void prologProxy( void setHasWarnings(boolean hasWarnings); - ServerPrepareResult addPrepareInCache(String key, ServerPrepareResult serverPrepareResult); + ServerPrepareResult putInCache(String key, ServerPrepareResult serverPrepareResult); void readEofPacket() throws SQLException, IOException; diff --git a/src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java b/src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java index 0ec088765..362ea8ee6 100644 --- a/src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java +++ b/src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java @@ -111,6 +111,11 @@ public synchronized ServerPrepareResult put(String key, ServerPrepareResult resu ServerPrepareResult cachedServerPrepareResult = super.get(key); // if there is already some cached data (and not been deallocate), return existing cached data if (cachedServerPrepareResult != null && cachedServerPrepareResult.incrementShareCounter()) { + try { + protocol.forceReleasePrepareStatement(result.getStatementId()); + } catch (SQLException e) { + // eat exception + } return cachedServerPrepareResult; } // if no cache data, or been deallocate, put new result in cache diff --git a/src/main/java/org/mariadb/jdbc/internal/util/dao/ServerPrepareResult.java b/src/main/java/org/mariadb/jdbc/internal/util/dao/ServerPrepareResult.java index a7c880960..bf2c1eead 100644 --- a/src/main/java/org/mariadb/jdbc/internal/util/dao/ServerPrepareResult.java +++ b/src/main/java/org/mariadb/jdbc/internal/util/dao/ServerPrepareResult.java @@ -52,7 +52,6 @@ package org.mariadb.jdbc.internal.util.dao; -import java.util.concurrent.atomic.AtomicBoolean; import org.mariadb.jdbc.internal.ColumnType; import org.mariadb.jdbc.internal.com.read.resultset.ColumnDefinition; import org.mariadb.jdbc.internal.protocol.Protocol; @@ -62,13 +61,13 @@ public class ServerPrepareResult implements PrepareResult { private final ColumnDefinition[] columns; private final ColumnDefinition[] parameters; private final String sql; - private final AtomicBoolean inCache = new AtomicBoolean(); private int statementId; private ColumnType[] parameterTypeHeader; private Protocol unProxiedProtocol; // share indicator private volatile int shareCounter = 1; private volatile boolean isBeingDeallocate; + private volatile boolean inCache; /** * PrepareStatement Result object. @@ -112,11 +111,11 @@ public void failover(int statementId, Protocol unProxiedProtocol) { } public void setAddToCache() { - inCache.set(true); + inCache = true; } public void setRemoveFromCache() { - inCache.set(false); + inCache = false; } /** @@ -148,7 +147,7 @@ public synchronized boolean canBeDeallocate() { if (shareCounter > 0 || isBeingDeallocate) { return false; } - if (!inCache.get()) { + if (!inCache) { isBeingDeallocate = true; return true; } diff --git a/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java b/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java index 71ed9007d..3394fe03f 100644 --- a/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java +++ b/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java @@ -91,6 +91,7 @@ public void autoReconnect() throws SQLException, InterruptedException { @Test public void autoReconnectPing() throws SQLException, InterruptedException { Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(runLongTest); try (Connection conn = setConnection("&autoReconnect")) { Statement stmt = conn.createStatement(); stmt.executeQuery("SELECT 1"); From 13c017587b8c91a4ceb87d1431f7a823fce9fb1f Mon Sep 17 00:00:00 2001 From: rusher Date: Wed, 18 Nov 2020 22:04:32 +0100 Subject: [PATCH 23/25] [misc] removing JDK 12 on travis (not available anymore) --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0a882db60..14264b634 100644 --- a/.travis.yml +++ b/.travis.yml @@ -79,8 +79,6 @@ matrix: jdk: openjdk11 - env: DB=mariadb:10.5 PACKET=40M COMPRESSION=true jdk: openjdk11 - - env: DB=mariadb:10.5 PACKET=8M - jdk: openjdk12 - env: DB=mariadb:10.5 PACKET=8M MAXSCALE_VERSION=2.5.3 MAXSCALE_TEST_DISABLE=true SSLPORT=4009 jdk: openjdk11 From f281de766fd2f25e9dd9affecaf2cf7b55d459eb Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 23 Nov 2020 15:59:19 +0100 Subject: [PATCH 24/25] [misc] travis SkySQL HA testing addition --- .travis.yml | 2 + .travis/script.sh | 27 +- .../jdbc/ClientSidePreparedStatement.java | 2 +- .../org/mariadb/jdbc/MariaDbSavepoint.java | 2 +- .../internal/com/send/ComStmtPrepare.java | 4 +- .../authentication/Sha256PasswordPlugin.java | 2 +- .../internal/protocol/AbstractMultiSend.java | 1 - .../protocol/AbstractQueryProtocol.java | 7 +- .../org/mariadb/jdbc/util/DefaultOptions.java | 20 +- .../mariadb/jdbc/AllowMultiQueriesTest.java | 21 +- .../org/mariadb/jdbc/AutoReconnectTest.java | 6 +- src/test/java/org/mariadb/jdbc/BaseTest.java | 139 +--- .../java/org/mariadb/jdbc/BasicBatchTest.java | 43 +- .../java/org/mariadb/jdbc/BigQueryTest.java | 37 +- src/test/java/org/mariadb/jdbc/BlobTest.java | 62 +- .../java/org/mariadb/jdbc/BooleanTest.java | 25 +- .../java/org/mariadb/jdbc/BufferTest.java | 14 +- src/test/java/org/mariadb/jdbc/ByteTest.java | 18 +- .../org/mariadb/jdbc/CallStatementTest.java | 90 +- .../java/org/mariadb/jdbc/CancelTest.java | 32 +- .../java/org/mariadb/jdbc/CheckDataTest.java | 31 +- .../ClientPreparedStatementParsingTest.java | 2 +- .../java/org/mariadb/jdbc/CollationTest.java | 43 +- .../jdbc/ComMultiPrepareStatementTest.java | 19 +- .../java/org/mariadb/jdbc/ConnectionTest.java | 40 +- .../mariadb/jdbc/CredentialPluginTest.java | 12 +- .../java/org/mariadb/jdbc/DataNTypeTest.java | 54 +- .../org/mariadb/jdbc/DataSourcePoolTest.java | 6 +- .../java/org/mariadb/jdbc/DataSourceTest.java | 24 +- .../org/mariadb/jdbc/DataTypeSignedTest.java | 33 +- .../mariadb/jdbc/DataTypeUnsignedTest.java | 46 +- .../mariadb/jdbc/DatabaseMetadataTest.java | 326 ++++---- .../jdbc/DatatypeCompatibilityTest.java | 135 +-- .../java/org/mariadb/jdbc/DatatypeTest.java | 226 ++--- src/test/java/org/mariadb/jdbc/DateTest.java | 111 ++- .../jdbc/DistributedTransactionTest.java | 26 +- .../java/org/mariadb/jdbc/DriverTest.java | 222 ++--- .../org/mariadb/jdbc/ErrorMessageTest.java | 48 +- .../org/mariadb/jdbc/ExecuteBatchTest.java | 102 +-- .../java/org/mariadb/jdbc/FetchSizeTest.java | 26 +- .../org/mariadb/jdbc/GeneratedKeysTest.java | 25 +- .../java/org/mariadb/jdbc/GeneratedTest.java | 21 +- .../java/org/mariadb/jdbc/GeometryTest.java | 18 +- .../jdbc/GiganticLoadDataInfileTest.java | 22 +- .../mariadb/jdbc/LocalInfileDisableTest.java | 21 +- .../jdbc/LocalInfileInputStreamTest.java | 47 +- .../jdbc/MariaDbCompatibilityTest.java | 23 +- .../jdbc/MariaDbDatabaseMetaDataTest.java | 20 +- .../jdbc/MariaDbPoolDataSourceTest.java | 31 +- src/test/java/org/mariadb/jdbc/MultiTest.java | 179 ++-- .../java/org/mariadb/jdbc/ParserTest.java | 21 +- .../mariadb/jdbc/PasswordEncodingTest.java | 8 +- .../mariadb/jdbc/PooledConnectionTest.java | 2 +- .../mariadb/jdbc/PreparedStatementTest.java | 97 ++- .../java/org/mariadb/jdbc/RePrepareTest.java | 24 +- .../ReconnectionStateMaxAllowedStatement.java | 24 +- .../mariadb/jdbc/ResultSetMetaDataTest.java | 38 +- .../java/org/mariadb/jdbc/ResultSetTest.java | 160 ++-- .../org/mariadb/jdbc/ScalarFunctionsTest.java | 30 +- .../java/org/mariadb/jdbc/ScrollTypeTest.java | 29 +- .../jdbc/ServerPrepareStatementTest.java | 204 ++--- src/test/java/org/mariadb/jdbc/SslTest.java | 10 +- .../org/mariadb/jdbc/StateChangeTest.java | 20 +- .../java/org/mariadb/jdbc/StatementTest.java | 77 +- .../org/mariadb/jdbc/StoredProcedureTest.java | 773 +++++++++--------- .../java/org/mariadb/jdbc/StringUTFTest.java | 20 +- .../java/org/mariadb/jdbc/TimeoutTest.java | 7 +- .../jdbc/TimezoneDaylightSavingTimeTest.java | 86 +- .../org/mariadb/jdbc/TransactionTest.java | 39 +- .../mariadb/jdbc/TruncateExceptionTest.java | 19 +- .../java/org/mariadb/jdbc/UnicodeTest.java | 40 +- .../org/mariadb/jdbc/UpdateResultSetTest.java | 235 +++--- .../jdbc/failover/AllowMasterDownTest.java | 30 +- .../mariadb/jdbc/failover/BaseMonoServer.java | 4 +- .../jdbc/failover/BaseReplication.java | 2 + .../jdbc/failover/MonoServerFailoverTest.java | 11 +- .../failover/ReplicationFailoverTest.java | 2 + .../tls/HostnameVerifierImplTest.java | 16 +- 78 files changed, 2568 insertions(+), 1953 deletions(-) diff --git a/.travis.yml b/.travis.yml index 14264b634..5a5d830f8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -39,6 +39,8 @@ matrix: jdk: openjdk11 - env: SKYSQL=true PACKET=8M jdk: openjdk11 + - env: SKYSQL_HA=true PACKET=8M + jdk: openjdk11 - env: DB=mysql:5.7 PACKET=8M jdk: openjdk11 - env: DB=mysql:8.0 PACKET=8M ADDITIONAL_CONF=--default-authentication-plugin=mysql_native_password --caching_sha2_password_private_key_path=/etc/sslcert/server.key --caching_sha2_password_public_key_path=/etc/sslcert/public.key diff --git a/.travis/script.sh b/.travis/script.sh index 804ef4fb1..461443812 100644 --- a/.travis/script.sh +++ b/.travis/script.sh @@ -6,16 +6,25 @@ set -e ################################################################################################################### # test different type of configuration ################################################################################################################### -if [ -n "$SKYSQL" ] ; then - - if [ -z "$SKYSQL_HOST" ] ; then - echo "No SkySQL configuration found !" - exit 0 +if [ -n "$SKYSQL" ] || [ -n "$SKYSQL_HA" ]; then + if [ -n "$SKYSQL" ]; then + if [ -z "$SKYSQL_HOST" ] ; then + echo "No SkySQL configuration found !" + exit 0 + else + testSingleHost=true + urlString="jdbc:mariadb://$SKYSQL_HOST:$SKYSQL_PORT/testj?user=$SKYSQL_USER&password=$SKYSQL_PASSWORD&enablePacketDebug=true&useSsl&serverSslCert=$SKYSQL_SSL_CA" + cmd=( mvn clean test $ADDITIONNAL_VARIABLES -DjobId=${TRAVIS_JOB_ID} ) + fi else - testSingleHost=true - urlString="jdbc:mariadb://$SKYSQL_HOST:$SKYSQL_PORT/testj?user=$SKYSQL_USER&password=$SKYSQL_PASSWORD&enablePacketDebug=true&useSsl&serverSslCert=$SKYSQL_SSL_CA" - - cmd=( mvn clean test $ADDITIONNAL_VARIABLES -DjobId=${TRAVIS_JOB_ID} ) + if [ -z "$SKYSQL_HA_HOST" ] ; then + echo "No SkySQL HA configuration found !" + exit 0 + else + testSingleHost=true + urlString="jdbc:mariadb://$SKYSQL_HA_HOST:$SKYSQL_HA_PORT/testj?user=$SKYSQL_HA_USER&password=$SKYSQL_HA_PASSWORD&enablePacketDebug=true&useSsl&serverSslCert=$SKYSQL_HA_SSL_CA" + cmd=( mvn clean test $ADDITIONNAL_VARIABLES -DjobId=${TRAVIS_JOB_ID} ) + fi fi else diff --git a/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java index 233a1b809..18912490d 100644 --- a/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java +++ b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java @@ -192,7 +192,7 @@ protected boolean executeInternal(int fetchSize) throws SQLException { logger.error("Parameter at position {} is not set", (i + 1)); throw exceptionFactory .raiseStatementError(connection, this) - .create("Parameter at position " + (i + 1) + " is " + "not set", "07004"); + .create("Parameter at position " + (i + 1) + " is not set", "07004"); } } diff --git a/src/main/java/org/mariadb/jdbc/MariaDbSavepoint.java b/src/main/java/org/mariadb/jdbc/MariaDbSavepoint.java index 2cbd89c7d..b4266f083 100644 --- a/src/main/java/org/mariadb/jdbc/MariaDbSavepoint.java +++ b/src/main/java/org/mariadb/jdbc/MariaDbSavepoint.java @@ -85,6 +85,6 @@ public String getSavepointName() { @Override public String toString() { - return "MariaDbSavepoint{" + "name='" + name + '\'' + '}'; + return "MariaDbSavepoint{name='" + name + '\'' + '}'; } } diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java b/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java index 3575f5318..7839b5947 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java @@ -78,6 +78,7 @@ public ComStmtPrepare(Protocol protocol, String sql) { * Send directly to socket the sql data. * * @param pos the writer + * @return ComStmtPrepare this object * @throws IOException if connection error occur */ public ComStmtPrepare send(PacketOutputStream pos) throws IOException { @@ -158,7 +159,8 @@ public ServerPrepareResult read(PacketInputStream reader, boolean eofDeprecated) String key = protocol.getDatabase() + "-" + sql; ServerPrepareResult cachedServerPrepareResult = protocol.putInCache(key, serverPrepareResult); - // if same prepare result is already cached, dismissed prepared result, and reuse cached entry + // if same prepare result is already cached, dismissed prepared result, and reuse cached + // entry return cachedServerPrepareResult != null ? cachedServerPrepareResult : serverPrepareResult; } return serverPrepareResult; diff --git a/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/Sha256PasswordPlugin.java b/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/Sha256PasswordPlugin.java index 716030768..b3cdced77 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/Sha256PasswordPlugin.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/Sha256PasswordPlugin.java @@ -229,7 +229,7 @@ public Buffer process(PacketOutputStream out, PacketInputStream in, AtomicIntege } else { if (!options.allowPublicKeyRetrieval) { throw new SQLException( - "RSA public key is not available client side (option " + "serverRsaPublicKeyFile)", + "RSA public key is not available client side (option serverRsaPublicKeyFile)", "S1009"); } diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java index 032255b2e..97a872147 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractMultiSend.java @@ -64,7 +64,6 @@ import java.util.concurrent.ThreadPoolExecutor; import org.mariadb.jdbc.internal.ColumnType; import org.mariadb.jdbc.internal.com.read.dao.Results; -import org.mariadb.jdbc.internal.com.send.ComStmtPrepare; import org.mariadb.jdbc.internal.com.send.parameters.ParameterHolder; import org.mariadb.jdbc.internal.io.output.PacketOutputStream; import org.mariadb.jdbc.internal.util.BulkStatus; diff --git a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java index 1d109c385..295f21130 100644 --- a/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java +++ b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java @@ -870,9 +870,7 @@ public ServerPrepareResult prepare(String sql, boolean executeOnMaster) throws S cmdPrologue(); - return new ComStmtPrepare(this, sql) - .send(writer) - .read(reader, eofDeprecated); + return new ComStmtPrepare(this, sql).send(writer).read(reader, eofDeprecated); } catch (IOException e) { throw exceptionWithQuery(sql, handleIoException(e), explicitClosed); @@ -1898,8 +1896,7 @@ public void prolog( connection.reenableWarnings(); } - public ServerPrepareResult putInCache( - String key, ServerPrepareResult serverPrepareResult) { + public ServerPrepareResult putInCache(String key, ServerPrepareResult serverPrepareResult) { return serverPrepareStatementCache.put(key, serverPrepareResult); } diff --git a/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java b/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java index eb283c41f..c240c8b84 100644 --- a/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java +++ b/src/main/java/org/mariadb/jdbc/util/DefaultOptions.java @@ -67,12 +67,12 @@ public enum DefaultOptions { "tcpAbortiveClose", Boolean.FALSE, "1.1.1", - "Sets corresponding option on the connection " + "socket.", + "Sets corresponding option on the connection socket.", false), LOCAL_SOCKET_ADDRESS( "localSocketAddress", "1.1.8", - "Hostname or IP address to bind the connection socket to a " + "local (UNIX domain) socket.", + "Hostname or IP address to bind the connection socket to a local (UNIX domain) socket.", false), SOCKET_TIMEOUT( "socketTimeout", @@ -120,7 +120,7 @@ public enum DefaultOptions { "createDatabaseIfNotExist", Boolean.FALSE, "1.1.8", - "the specified database in the " + "url will be created if non-existent.", + "the specified database in the url will be created if non-existent.", false), SERVER_TIMEZONE( "serverTimezone", @@ -133,7 +133,7 @@ public enum DefaultOptions { "nullCatalogMeansCurrent", Boolean.TRUE, "1.1.8", - "DatabaseMetaData use current catalog" + " if null.", + "DatabaseMetaData use current catalog if null.", false), TINY_INT_IS_BIT( "tinyInt1isBit", @@ -212,7 +212,7 @@ public enum DefaultOptions { "trustServerCertificate", Boolean.FALSE, "1.1.1", - "When using SSL, do not check server's" + " certificate.", + "When using SSL, do not check server's certificate.", false), SERVER_SSL_CERT( "serverSslCert", @@ -278,7 +278,7 @@ public enum DefaultOptions { 50, 0, "1.2.0", - "time in second a server is" + " blacklisted after a connection failure.", + "time in second a server is blacklisted after a connection failure.", false), CACHE_PREP_STMTS( "cachePrepStmts", @@ -388,7 +388,7 @@ public enum DefaultOptions { "continueBatchOnError", Boolean.TRUE, "1.4.0", - "When executing batch queries, must batch " + "continue on error.", + "When executing batch queries, must batch continue on error.", false), JDBC_COMPLIANT_TRUNCATION( "jdbcCompliantTruncation", @@ -458,12 +458,12 @@ public enum DefaultOptions { null, 0L, "1.5.0", - "Will log query with execution time superior" + " to this value (if defined )", + "Will log query with execution time superior to this value (if defined )", false), PASSWORD_CHARACTER_ENCODING( "passwordCharacterEncoding", "1.5.9", - "Indicate password encoding charset. If not set," + " driver use platform's default charset.", + "Indicate password encoding charset. If not set, driver use platform's default charset.", false), PIPELINE_AUTH( "usePipelineAuth", @@ -525,7 +525,7 @@ public enum DefaultOptions { 8, 1, "2.2.0", - "The maximum number of physical connections that the pool should " + "contain.", + "The maximum number of physical connections that the pool should contain.", false), MIN_POOL_SIZE( "minPoolSize", diff --git a/src/test/java/org/mariadb/jdbc/AllowMultiQueriesTest.java b/src/test/java/org/mariadb/jdbc/AllowMultiQueriesTest.java index 2cc65508d..bc2dc539e 100644 --- a/src/test/java/org/mariadb/jdbc/AllowMultiQueriesTest.java +++ b/src/test/java/org/mariadb/jdbc/AllowMultiQueriesTest.java @@ -58,6 +58,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -70,17 +71,25 @@ public class AllowMultiQueriesTest extends BaseTest { */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "AllowMultiQueriesTest", "id int not null primary key auto_increment, test varchar(10)"); - createTable( - "AllowMultiQueriesTest2", "id int not null primary key auto_increment, test varchar(10)"); - if (testSingleHost) { - try (Statement stmt = sharedConnection.createStatement()) { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE AllowMultiQueriesTest(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE AllowMultiQueriesTest2(id int not null primary key auto_increment, test varchar(10))"); + if (testSingleHost) { stmt.execute("INSERT INTO AllowMultiQueriesTest(test) VALUES ('a'), ('b')"); } } } + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE AllowMultiQueriesTest"); + stmt.execute("DROP TABLE AllowMultiQueriesTest2"); + } + } + @Test public void allowMultiQueriesSingleTest() throws SQLException { try (Connection connection = setConnection("&allowMultiQueries=true")) { diff --git a/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java b/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java index 3394fe03f..914d84d7f 100644 --- a/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java +++ b/src/test/java/org/mariadb/jdbc/AutoReconnectTest.java @@ -62,7 +62,9 @@ public class AutoReconnectTest extends BaseTest { @Test public void autoReconnect() throws SQLException, InterruptedException { Assume.assumeTrue( - System.getenv("MAXSCALE_TEST_DISABLE") == null && System.getenv("SKYSQL") == null); + System.getenv("MAXSCALE_TEST_DISABLE") == null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); try (Connection conn = setConnection("&autoReconnect")) { Statement stmt = conn.createStatement(); stmt.executeQuery("SELECT 1"); @@ -90,7 +92,7 @@ public void autoReconnect() throws SQLException, InterruptedException { @Test public void autoReconnectPing() throws SQLException, InterruptedException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(runLongTest); try (Connection conn = setConnection("&autoReconnect")) { Statement stmt = conn.createStatement(); diff --git a/src/test/java/org/mariadb/jdbc/BaseTest.java b/src/test/java/org/mariadb/jdbc/BaseTest.java index 20456aedb..bf3d625a9 100644 --- a/src/test/java/org/mariadb/jdbc/BaseTest.java +++ b/src/test/java/org/mariadb/jdbc/BaseTest.java @@ -102,10 +102,6 @@ public class BaseTest { } } - private static final Set tempTableList = new HashSet<>(); - private static final Set tempViewList = new HashSet<>(); - private static final Set tempProcedureList = new HashSet<>(); - private static final Set tempFunctionList = new HashSet<>(); private static final NumberFormat numberFormat = DecimalFormat.getInstance(Locale.ROOT); protected static String connU; protected static String connUri; @@ -130,6 +126,7 @@ public class BaseTest { private long ttime; protected void starting(Description description) { + if (testSingleHost) { System.out.println( "start test : " + description.getClassName() + "." + description.getMethodName()); @@ -150,7 +147,7 @@ protected void finished(Description description) { } catch (SQLNonTransientConnectionException connFail) { connFail.printStackTrace(); try { - before(); + aBefore(); } catch (SQLException e) { System.out.println("ERROR reconnecting"); e.printStackTrace(); @@ -205,7 +202,7 @@ protected void failed(Throwable throwable, Description description) { * @throws SQLException exception */ @BeforeClass() - public static void before() throws SQLException { + public static void aBefore() throws SQLException { String url = System.getProperty("dbUrl", mDefUrl); runLongTest = Boolean.parseBoolean(System.getProperty("runLongTest", "false")); testSingleHost = Boolean.parseBoolean(System.getProperty("testSingleHost", "true")); @@ -289,47 +286,6 @@ private static void setUri() { @AfterClass public static void after() throws SQLException { if (testSingleHost && sharedConnection != null && !sharedConnection.isClosed()) { - if (!tempViewList.isEmpty()) { - Statement stmt = sharedConnection.createStatement(); - for (String viewName : tempViewList) { - try { - stmt.execute("DROP VIEW IF EXISTS " + viewName); - } catch (SQLException e) { - // eat exception - } - } - } - if (!tempTableList.isEmpty()) { - Statement stmt = sharedConnection.createStatement(); - for (String tableName : tempTableList) { - try { - stmt.execute("DROP TABLE IF EXISTS " + tableName); - } catch (SQLException e) { - // eat exception - } - } - } - if (!tempProcedureList.isEmpty()) { - Statement stmt = sharedConnection.createStatement(); - for (String procedureName : tempProcedureList) { - try { - stmt.execute("DROP procedure IF EXISTS " + procedureName); - } catch (SQLException e) { - // eat exception - } - } - } - if (!tempFunctionList.isEmpty()) { - Statement stmt = sharedConnection.createStatement(); - for (String functionName : tempFunctionList) { - try { - stmt.execute("DROP FUNCTION IF EXISTS " + functionName); - } catch (SQLException e) { - // eat exception - } - } - } - try { sharedConnection.close(); } catch (SQLException e) { @@ -359,91 +315,6 @@ static void logInfo(String message) { System.out.println(message); } - /** - * Create a table that will be detroyed a the end of tests. - * - * @param tableName table name - * @param tableColumns table columns - * @throws SQLException exception - */ - public static void createTable(String tableName, String tableColumns) throws SQLException { - createTable(tableName, tableColumns, null); - } - - /** - * Create a table that will be detroyed a the end of tests. - * - * @param tableName table name - * @param tableColumns table columns - * @param engine engine type - * @throws SQLException exception - */ - public static void createTable(String tableName, String tableColumns, String engine) - throws SQLException { - if (testSingleHost) { - Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists " + tableName); - stmt.execute( - "create table " - + tableName - + " (" - + tableColumns - + ") " - + ((engine != null) ? engine : "")); - if (!tempFunctionList.contains(tableName)) { - tempTableList.add(tableName); - } - } - } - - /** - * Create a view that will be detroyed a the end of tests. - * - * @param viewName table name - * @param tableColumns table columns - * @throws SQLException exception - */ - public static void createView(String viewName, String tableColumns) throws SQLException { - if (testSingleHost) { - Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop view if exists " + viewName); - stmt.execute("create view " + viewName + " AS (" + tableColumns + ") "); - tempViewList.add(viewName); - } - } - - /** - * Create procedure that will be delete on end of test. - * - * @param name procedure name - * @param body procecure body - * @throws SQLException exception - */ - public static void createProcedure(String name, String body) throws SQLException { - if (testSingleHost) { - Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop procedure IF EXISTS " + name); - stmt.execute("create procedure " + name + body); - tempProcedureList.add(name); - } - } - - /** - * Create function that will be delete on end of test. - * - * @param name function name - * @param body function body - * @throws SQLException exception - */ - public static void createFunction(String name, String body) throws SQLException { - if (testSingleHost) { - Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop function IF EXISTS " + name); - stmt.execute("create function " + name + body); - tempFunctionList.add(name); - } - } - /** * Check if current DB server is MariaDB. * @@ -937,7 +808,7 @@ public boolean haveSsl(Connection connection) { * @param minor database minor version * @throws SQLException exception */ - public boolean minVersion(int major, int minor) throws SQLException { + public static boolean minVersion(int major, int minor) throws SQLException { DatabaseMetaData md = sharedConnection.getMetaData(); int dbMajor = md.getDatabaseMajorVersion(); int dbMinor = md.getDatabaseMinorVersion(); @@ -951,7 +822,7 @@ public boolean minVersion(int major, int minor) throws SQLException { * @param minor database minor version * @throws SQLException exception */ - public boolean strictBeforeVersion(int major, int minor) throws SQLException { + public static boolean strictBeforeVersion(int major, int minor) throws SQLException { DatabaseMetaData md = sharedConnection.getMetaData(); int dbMajor = md.getDatabaseMajorVersion(); int dbMinor = md.getDatabaseMinorVersion(); diff --git a/src/test/java/org/mariadb/jdbc/BasicBatchTest.java b/src/test/java/org/mariadb/jdbc/BasicBatchTest.java index 1a5a764b4..c22128495 100644 --- a/src/test/java/org/mariadb/jdbc/BasicBatchTest.java +++ b/src/test/java/org/mariadb/jdbc/BasicBatchTest.java @@ -55,6 +55,7 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -68,16 +69,37 @@ public class BasicBatchTest extends BaseTest { */ @BeforeClass() public static void initClass() throws SQLException { - createTable("test_batch", "id int not null primary key auto_increment, test varchar(10)"); - createTable("test_batch2", "id int not null primary key auto_increment, test varchar(10)"); - createTable("test_batch3", "id int not null primary key auto_increment, test varchar(10)"); - createTable("batchUpdateException", "i int,PRIMARY KEY (i)"); - createTable("batchPrepareUpdateException", "i int,PRIMARY KEY (i)"); - createTable( - "rewritetest", "id int not null primary key, a varchar(10), b int", "engine=innodb"); - createTable( - "rewritetest2", "id int not null primary key, a varchar(10), b int", "engine=innodb"); - createTable("bug501452", "id int not null primary key, value varchar(20)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE test_batch(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE test_batch2(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE test_batch3(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute("CREATE TABLE batchUpdateException(i int,PRIMARY KEY (i))"); + stmt.execute("CREATE TABLE batchPrepareUpdateException(i int,PRIMARY KEY (i))"); + stmt.execute( + "CREATE TABLE rewritetest(id int not null primary key, a varchar(10), b int) engine=innodb"); + stmt.execute( + "CREATE TABLE rewritetest2(id int not null primary key, a varchar(10), b int) engine=innodb"); + stmt.execute("CREATE TABLE bug501452(id int not null primary key, value varchar(20))"); + stmt.execute("CREATE TABLE testBatchString(charValue VARCHAR(100) NOT NULL)"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE test_batch"); + stmt.execute("DROP TABLE test_batch2"); + stmt.execute("DROP TABLE test_batch3"); + stmt.execute("DROP TABLE batchUpdateException"); + stmt.execute("DROP TABLE batchPrepareUpdateException"); + stmt.execute("DROP TABLE rewritetest"); + stmt.execute("DROP TABLE rewritetest2"); + stmt.execute("DROP TABLE bug501452"); + stmt.execute("DROP TABLE testBatchString"); + } } @Test @@ -343,7 +365,6 @@ public void testBatchString() throws SQLException { Assume.assumeTrue( runLongTest && (sharedOptions().useBulkStmts || sharedIsRewrite())); // if not will be too long. - createTable("testBatchString", "charValue VARCHAR(100) NOT NULL"); Statement stmt = sharedConnection.createStatement(); String[] datas = new String[1_000_000]; String empty = diff --git a/src/test/java/org/mariadb/jdbc/BigQueryTest.java b/src/test/java/org/mariadb/jdbc/BigQueryTest.java index 44f1192e4..3932e2c25 100644 --- a/src/test/java/org/mariadb/jdbc/BigQueryTest.java +++ b/src/test/java/org/mariadb/jdbc/BigQueryTest.java @@ -58,6 +58,7 @@ import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.Arrays; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -71,16 +72,32 @@ public class BigQueryTest extends BaseTest { */ @BeforeClass() public static void initClass() throws SQLException { - createTable("bigblob", "id int not null primary key auto_increment, test longblob"); - createTable( - "bigblob2", "id int not null primary key auto_increment, test longblob, test2 longblob"); - createTable( - "bigblob3", - "id int not null primary key auto_increment, test longblob, test2 longblob, test3 varchar(20)"); - createTable("bigblob4", "test longblob"); - createTable( - "bigblob5", "id int not null primary key auto_increment, test longblob, test2 text"); - createTable("bigblob6", "id int not null primary key auto_increment, test longblob"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE bigblob(id int not null primary key auto_increment, test longblob)"); + stmt.execute( + "CREATE TABLE bigblob2(id int not null primary key auto_increment, test longblob, test2 longblob)"); + stmt.execute( + "CREATE TABLE bigblob3(id int not null primary key auto_increment, test longblob, test2 longblob, test3 varchar(20))"); + stmt.execute("CREATE TABLE bigblob4(test longblob)"); + stmt.execute( + "CREATE TABLE bigblob5(id int not null primary key auto_increment, test longblob, test2 text)"); + stmt.execute( + "CREATE TABLE bigblob6(id int not null primary key auto_increment, test longblob)"); + stmt.execute("FLUSH TABLE"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE bigblob"); + stmt.execute("DROP TABLE bigblob2"); + stmt.execute("DROP TABLE bigblob3"); + stmt.execute("DROP TABLE bigblob4"); + stmt.execute("DROP TABLE bigblob5"); + stmt.execute("DROP TABLE bigblob6"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/BlobTest.java b/src/test/java/org/mariadb/jdbc/BlobTest.java index bf68b18cd..ed543c450 100644 --- a/src/test/java/org/mariadb/jdbc/BlobTest.java +++ b/src/test/java/org/mariadb/jdbc/BlobTest.java @@ -61,6 +61,7 @@ import java.sql.*; import java.util.Arrays; import java.util.Random; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -74,25 +75,47 @@ public class BlobTest extends BaseTest { */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "bug716378", - "id int not null primary key auto_increment, test longblob, test2 blob, test3 text"); - createTable( - "BlobTeststreamtest2", - "id int primary key not null, st varchar(20), strm text" + ", strm2 text, strm3 text", - "CHARSET utf8"); - createTable("BlobTeststreamtest3", "id int primary key not null, strm text", "CHARSET utf8"); - createTable("BlobTestclobtest", "id int not null primary key, strm text", "CHARSET utf8"); - createTable("BlobTestclobtest2", "strm text", "CHARSET utf8"); - createTable("BlobTestclobtest3", "id int not null primary key, strm text", "CHARSET utf8"); - createTable("BlobTestclobtest4", "id int not null primary key, strm text", "CHARSET utf8"); - createTable("BlobTestclobtest5", "id int not null primary key, strm text", "CHARSET utf8"); - createTable("BlobTestblobtest", "id int not null primary key, strm blob"); - createTable("BlobTestblobtest2", "id int not null primary key, strm blob"); - createTable( - "conj77_test", - "Name VARCHAR(100) NOT NULL,Archive LONGBLOB, PRIMARY KEY (Name)", - "Engine=InnoDB DEFAULT CHARSET utf8"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE bug716378(id int not null primary key auto_increment, test longblob, test2 blob, test3 text)"); + stmt.execute( + "CREATE TABLE BlobTeststreamtest2(id int primary key not null, st varchar(20), strm text, strm2 text, strm3 text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE BlobTeststreamtest3(id int primary key not null, strm text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE BlobTestclobtest(id int not null primary key, strm text) CHARSET utf8"); + stmt.execute("CREATE TABLE BlobTestclobtest2(strm text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE BlobTestclobtest3(id int not null primary key, strm text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE BlobTestclobtest4(id int not null primary key, strm text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE BlobTestclobtest5(id int not null primary key, strm text) CHARSET utf8"); + stmt.execute("CREATE TABLE BlobTestblobtest(id int not null primary key, strm blob)"); + stmt.execute("CREATE TABLE BlobTestblobtest2(id int not null primary key, strm blob)"); + stmt.execute( + "CREATE TABLE conj77_test(Name VARCHAR(100) NOT NULL,Archive LONGBLOB, PRIMARY KEY (Name)) Engine=InnoDB DEFAULT CHARSET utf8"); + stmt.execute("CREATE TABLE emptyBlob(test longblob, test2 text, test3 text)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE bug716378"); + stmt.execute("DROP TABLE BlobTeststreamtest2"); + stmt.execute("DROP TABLE BlobTeststreamtest3"); + stmt.execute("DROP TABLE BlobTestclobtest"); + stmt.execute("DROP TABLE BlobTestclobtest2"); + stmt.execute("DROP TABLE BlobTestclobtest3"); + stmt.execute("DROP TABLE BlobTestclobtest4"); + stmt.execute("DROP TABLE BlobTestclobtest5"); + stmt.execute("DROP TABLE BlobTestblobtest"); + stmt.execute("DROP TABLE BlobTestblobtest2"); + stmt.execute("DROP TABLE conj77_test"); + stmt.execute("DROP TABLE emptyBlob"); + } } @Test @@ -459,7 +482,6 @@ public void conj77() throws Exception { @Test public void sendEmptyBlobPreparedQuery() throws SQLException { - createTable("emptyBlob", "test longblob, test2 text, test3 text"); try (Connection conn = setConnection()) { PreparedStatement ps = conn.prepareStatement("insert into emptyBlob values(?,?,?)"); ps.setBlob(1, new MariaDbBlob(new byte[0])); diff --git a/src/test/java/org/mariadb/jdbc/BooleanTest.java b/src/test/java/org/mariadb/jdbc/BooleanTest.java index 42531d4ba..92895e82e 100644 --- a/src/test/java/org/mariadb/jdbc/BooleanTest.java +++ b/src/test/java/org/mariadb/jdbc/BooleanTest.java @@ -55,6 +55,7 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -67,12 +68,24 @@ public class BooleanTest extends BaseTest { */ @BeforeClass() public static void initClass() throws SQLException { - createTable("booleantest", "id int not null primary key auto_increment, test boolean"); - createTable("booleanvalue", "test boolean"); - createTable( - "booleanAllField", - "t1 BIT, t2 TINYINT(1), t3 SMALLINT(1), t4 MEDIUMINT(1), t5 INT(1), t6 BIGINT(1), t7 DECIMAL(1), t8 FLOAT, " - + "t9 DOUBLE, t10 CHAR(1), t11 VARCHAR(1), t12 BINARY(1), t13 BLOB(1), t14 TEXT(1)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE booleantest(id int not null primary key auto_increment, test boolean)"); + stmt.execute("CREATE TABLE booleanvalue(test boolean)"); + stmt.execute( + "CREATE TABLE booleanAllField(t1 BIT, t2 TINYINT(1), t3 SMALLINT(1), t4 MEDIUMINT(1), t5 INT(1), t6 BIGINT(1), t7 DECIMAL(1), t8 FLOAT, " + + "t9 DOUBLE, t10 CHAR(1), t11 VARCHAR(1), t12 BINARY(1), t13 BLOB(1), t14 TEXT(1))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE booleantest"); + stmt.execute("DROP TABLE booleanvalue"); + stmt.execute("DROP TABLE booleanAllField"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/BufferTest.java b/src/test/java/org/mariadb/jdbc/BufferTest.java index d6b2e40a9..9a62dff70 100644 --- a/src/test/java/org/mariadb/jdbc/BufferTest.java +++ b/src/test/java/org/mariadb/jdbc/BufferTest.java @@ -55,6 +55,7 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -82,7 +83,18 @@ public class BufferTest extends BaseTest { @BeforeClass() public static void initClass() throws SQLException { - createTable("buffer_test", "test longText"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE buffer_test(test longText)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS buffer_test"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/ByteTest.java b/src/test/java/org/mariadb/jdbc/ByteTest.java index 977498640..628c001bf 100644 --- a/src/test/java/org/mariadb/jdbc/ByteTest.java +++ b/src/test/java/org/mariadb/jdbc/ByteTest.java @@ -56,6 +56,7 @@ import static org.junit.Assert.assertTrue; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -64,14 +65,24 @@ public class ByteTest extends BaseTest { @BeforeClass() public static void initClass() throws SQLException { - createTable("ByteTest", "test tinyint, test2 TINYBLOB"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE ByteTest(test tinyint, test2 TINYBLOB)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE ByteTest"); + } } @Test public void byteSending() throws SQLException { Assume.assumeFalse(sharedUsePrepare()); try (PreparedStatement prep = - sharedConnection.prepareStatement("INSERT INTO ByteTest value " + "(?, ?)")) { + sharedConnection.prepareStatement("INSERT INTO ByteTest value (?, ?)")) { prep.setByte(1, (byte) -6); prep.setByte(2, (byte) -6); prep.execute(); @@ -88,8 +99,7 @@ public void byteSending() throws SQLException { @Test public void byteSendingBinary() throws SQLException { try (Connection conn = setConnection("&useServerPrepStmts")) { - try (PreparedStatement prep = - conn.prepareStatement("INSERT INTO ByteTest value " + "(?, ?)")) { + try (PreparedStatement prep = conn.prepareStatement("INSERT INTO ByteTest value (?, ?)")) { prep.setByte(1, (byte) -6); prep.setByte(2, (byte) -6); prep.execute(); diff --git a/src/test/java/org/mariadb/jdbc/CallStatementTest.java b/src/test/java/org/mariadb/jdbc/CallStatementTest.java index 1b17b37a2..3dba30f08 100644 --- a/src/test/java/org/mariadb/jdbc/CallStatementTest.java +++ b/src/test/java/org/mariadb/jdbc/CallStatementTest.java @@ -55,33 +55,63 @@ import static org.junit.Assert.*; import java.sql.*; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; public class CallStatementTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createProcedure("useParameterName", "(a int) begin select a; end"); - createProcedure("useWrongParameterName", "(a int) begin select a; end"); - createProcedure("multiResultSets", "() BEGIN SELECT 1; SELECT 2; END"); - createProcedure("inoutParam", "(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); - createProcedure("testGetProcedures", "(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); - createProcedure("withStrangeParameter", "(IN a DECIMAL(10,2)) begin select a; end"); - createProcedure( - "TEST_SP1", - "() BEGIN\n" - + "SELECT @Something := 'Something';\n" - + "SIGNAL SQLSTATE '70100'\n" - + "SET MESSAGE_TEXT = 'Test error from SP'; \n" - + "END"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE PROCEDURE useParameterName(a int) begin select a; end"); + stmt.execute("CREATE PROCEDURE useWrongParameterName(a int) begin select a; end"); + stmt.execute("CREATE PROCEDURE multiResultSets() BEGIN SELECT 1; SELECT 2; END"); + stmt.execute("CREATE PROCEDURE inoutParam(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); + stmt.execute("CREATE PROCEDURE testGetProcedures(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); + stmt.execute("CREATE PROCEDURE withStrangeParameter(IN a DECIMAL(10,2)) begin select a; end"); + stmt.execute( + "CREATE PROCEDURE TEST_SP1() BEGIN\n" + + "SELECT @Something := 'Something';\n" + + "SIGNAL SQLSTATE '70100'\n" + + "SET MESSAGE_TEXT = 'Test error from SP'; \n" + + "END"); + stmt.execute("CREATE PROCEDURE testCallWithFetchSize()\nBEGIN\nSELECT 1;SELECT 2;\nEND"); + stmt.execute("CREATE PROCEDURE prepareWithNoParameters()\nbegin\n SELECT 'mike';end\n"); + stmt.execute("CREATE PROCEDURE testMetaCatalog(x int, out y int)\nBEGIN\nSELECT 1;end\n"); + stmt.execute("CREATE PROCEDURE callabletest1()\nBEGIN\nSELECT 1;end\n"); + stmt.execute("CREATE PROCEDURE stmtSimple(IN p1 INT, IN p2 INT) begin SELECT p1 + p2; end\n"); + stmt.execute( + "CREATE PROCEDURE prepareStmtSimple(IN p1 INT, IN p2 INT) begin SELECT p1 + p2; end\n"); + stmt.execute( + "CREATE FUNCTION stmtSimpleFunction(a float, b bigint, c int) RETURNS INT NO SQL\nBEGIN\nRETURN a;\nEND"); + stmt.execute( + "CREATE PROCEDURE prepareStmtWithOutParameter(x int, INOUT y int)\nBEGIN\nSELECT 1;end\n"); + stmt.execute("CREATE PROCEDURE testMetaWildcard(x int, out y int)\nBEGIN\nSELECT 1;end\n"); + + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP PROCEDURE IF EXISTS useParameterName"); + stmt.execute("DROP PROCEDURE IF EXISTS useWrongParameterName"); + stmt.execute("DROP PROCEDURE IF EXISTS multiResultSets"); + stmt.execute("DROP PROCEDURE IF EXISTS inoutParam"); + stmt.execute("DROP PROCEDURE IF EXISTS testGetProcedures"); + stmt.execute("DROP PROCEDURE IF EXISTS withStrangeParameter"); + stmt.execute("DROP PROCEDURE IF EXISTS TEST_SP1"); + stmt.execute("DROP PROCEDURE IF EXISTS testCallWithFetchSize"); + stmt.execute("DROP PROCEDURE IF EXISTS prepareWithNoParameters"); + stmt.execute("DROP PROCEDURE IF EXISTS testMetaCatalog"); + stmt.execute("DROP PROCEDURE IF EXISTS callabletest1"); + stmt.execute("DROP PROCEDURE IF EXISTS stmtSimple"); + stmt.execute("DROP PROCEDURE IF EXISTS prepareStmtSimple"); + stmt.execute("DROP FUNCTION IF EXISTS stmtSimpleFunction"); + stmt.execute("DROP PROCEDURE IF EXISTS prepareStmtWithOutParameter"); + stmt.execute("DROP PROCEDURE IF EXISTS testMetaWildcard"); + } } @Before @@ -91,7 +121,6 @@ public void checkSp() throws SQLException { @Test public void stmtSimple() throws SQLException { - createProcedure("stmtSimple", "(IN p1 INT, IN p2 INT) begin SELECT p1 + p2; end\n"); ResultSet rs = sharedConnection.createStatement().executeQuery("{call stmtSimple(2,2)}"); assertTrue(rs.next()); int result = rs.getInt(1); @@ -100,7 +129,6 @@ public void stmtSimple() throws SQLException { @Test public void prepareStmtSimple() throws SQLException { - createProcedure("prepareStmtSimple", "(IN p1 INT, IN p2 INT) begin SELECT p1 + p2; end\n"); PreparedStatement preparedStatement = sharedConnection.prepareStatement("{call prepareStmtSimple(?,?)}"); preparedStatement.setInt(1, 2); @@ -114,9 +142,6 @@ public void prepareStmtSimple() throws SQLException { @Test public void stmtSimpleFunction() throws SQLException { try { - createFunction( - "stmtSimpleFunction", - "(a float, b bigint, c int) RETURNS INT NO SQL\nBEGIN\nRETURN a;\nEND"); sharedConnection.createStatement().execute("{call stmtSimpleFunction(2,2,2)}"); fail("call mustn't work for function, use SELECT "); } catch (SQLSyntaxErrorException sqle) { @@ -129,9 +154,6 @@ public void stmtSimpleFunction() throws SQLException { @Test public void prepareStmtSimpleFunction() throws SQLException { try { - createFunction( - "stmtSimpleFunction", - "(a float, b bigint, c int) RETURNS INT NO SQL\nBEGIN\nRETURN a;\nEND"); PreparedStatement preparedStatement = sharedConnection.prepareStatement("{call stmtSimpleFunction(?,?,?)}"); preparedStatement.setInt(1, 2); @@ -149,8 +171,6 @@ public void prepareStmtSimpleFunction() throws SQLException { @Test public void prepareStmtWithOutParameter() throws SQLException { Assume.assumeTrue(sharedUsePrepare()); - createProcedure( - "prepareStmtWithOutParameter", "(x int, INOUT y int)\n" + "BEGIN\n" + "SELECT 1;end\n"); PreparedStatement preparedStatement = sharedConnection.prepareStatement("{call prepareStmtWithOutParameter(?,?)}"); preparedStatement.setInt(1, 2); @@ -244,7 +264,6 @@ public void getProcedures() throws SQLException { @Test public void meta() throws Exception { - createProcedure("callabletest1", "()\nBEGIN\nSELECT 1;end\n"); ResultSet rs = sharedConnection.getMetaData().getProcedures(null, null, "callabletest1"); if (rs.next()) { assertTrue("callabletest1".equals(rs.getString(3))); @@ -255,7 +274,6 @@ public void meta() throws Exception { @Test public void testMetaWildcard() throws Exception { - createProcedure("testMetaWildcard", "(x int, out y int)\n" + "BEGIN\n" + "SELECT 1;end\n"); ResultSet rs = sharedConnection.getMetaData().getProcedureColumns(null, null, "testMetaWildcard%", "%"); if (rs.next()) { @@ -271,7 +289,6 @@ public void testMetaWildcard() throws Exception { @Test public void testMetaCatalog() throws Exception { - createProcedure("testMetaCatalog", "(x int, out y int)\nBEGIN\nSELECT 1;end\n"); ResultSet rs = sharedConnection .getMetaData() @@ -293,8 +310,6 @@ public void testMetaCatalog() throws Exception { @Test public void prepareWithNoParameters() throws SQLException { - createProcedure("prepareWithNoParameters", "()\n" + "begin\n" + " SELECT 'mike';" + "end\n"); - PreparedStatement preparedStatement = sharedConnection.prepareStatement("{call prepareWithNoParameters()}"); ResultSet rs = preparedStatement.executeQuery(); @@ -304,7 +319,6 @@ public void prepareWithNoParameters() throws SQLException { @Test public void testCallWithFetchSize() throws SQLException { - createProcedure("testCallWithFetchSize", "()\nBEGIN\nSELECT 1;SELECT 2;\nEND"); try (Statement statement = sharedConnection.createStatement()) { statement.setFetchSize(1); try (ResultSet resultSet = statement.executeQuery("CALL testCallWithFetchSize()")) { diff --git a/src/test/java/org/mariadb/jdbc/CancelTest.java b/src/test/java/org/mariadb/jdbc/CancelTest.java index dc06e5bb0..b2f9cf276 100644 --- a/src/test/java/org/mariadb/jdbc/CancelTest.java +++ b/src/test/java/org/mariadb/jdbc/CancelTest.java @@ -59,18 +59,35 @@ import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class CancelTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE timeoutBatch(id int not null primary key auto_increment, aa text)"); + stmt.execute("CREATE TABLE timeoutBatch2(aa text)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS timeoutBatch"); + stmt.execute("DROP TABLE IF EXISTS timeoutBatch2"); + } + } + @Before public void cancelSupported() throws SQLException { requireMinimumVersion(5, 0); Assume.assumeTrue( - System.getenv("SKYSQL") == null && System.getenv("MAXSCALE_TEST_DISABLE") == null); + System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null + && System.getenv("MAXSCALE_TEST_DISABLE") == null); } @Test @@ -122,7 +139,6 @@ public void timeoutPrepareSleep() throws Exception { public void timeoutBatch() throws Exception { Assume.assumeFalse(sharedIsAurora()); Assume.assumeTrue(!sharedOptions().allowMultiQueries && !sharedIsRewrite()); - createTable("timeoutBatch", "id int not null primary key auto_increment, aa text"); try (Connection connection = setConnection("&maxQuerySizeToLog=92")) { Statement stmt = connection.createStatement(); @@ -150,13 +166,13 @@ public void timeoutPrepareBatch() throws Exception { Assume.assumeFalse(sharedIsAurora()); Assume.assumeTrue(!sharedOptions().allowMultiQueries && !sharedIsRewrite()); Assume.assumeTrue(!(sharedOptions().useBulkStmts && isMariadbServer() && minVersion(10, 2))); - createTable("timeoutBatch", "aa text"); + try (Connection tmpConnection = openNewConnection(connUri, new Properties())) { char[] arr = new char[1000]; Arrays.fill(arr, 'a'); String str = String.valueOf(arr); try (PreparedStatement stmt = - tmpConnection.prepareStatement("INSERT INTO timeoutBatch VALUES (?)")) { + tmpConnection.prepareStatement("INSERT INTO timeoutBatch2 VALUES (?)")) { stmt.setQueryTimeout(1); for (int i = 0; i < 20000; i++) { stmt.setString(1, str); diff --git a/src/test/java/org/mariadb/jdbc/CheckDataTest.java b/src/test/java/org/mariadb/jdbc/CheckDataTest.java index aa9223531..3601264e4 100644 --- a/src/test/java/org/mariadb/jdbc/CheckDataTest.java +++ b/src/test/java/org/mariadb/jdbc/CheckDataTest.java @@ -58,14 +58,40 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; public class CheckDataTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE CheckDataTest1(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE CheckDataTest2(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE CheckDataTest3(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE CheckDataTest4(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE CheckDataTest1"); + stmt.execute("DROP TABLE CheckDataTest2"); + stmt.execute("DROP TABLE CheckDataTest3"); + stmt.execute("DROP TABLE CheckDataTest4"); + } + } + @Test public void testStatementExecuteAutoincrement() throws SQLException { - createTable("CheckDataTest1", "id int not null primary key auto_increment, test varchar(10)"); Statement stmt = sharedConnection.createStatement(); int insert = stmt.executeUpdate( @@ -89,7 +115,6 @@ public void testStatementExecuteAutoincrement() throws SQLException { @Test public void testStatementBatch() throws SQLException { Assume.assumeFalse(isGalera()); - createTable("CheckDataTest2", "id int not null primary key auto_increment, test varchar(10)"); Statement stmt = sharedConnection.createStatement(); stmt.addBatch("INSERT INTO CheckDataTest2 (id, test) VALUES (2, 'test1')"); stmt.addBatch("INSERT INTO CheckDataTest2 (test) VALUES ('test2')"); @@ -129,7 +154,6 @@ public void testStatementBatch() throws SQLException { @Test public void testPrepareStatementExecuteAutoincrement() throws SQLException { - createTable("CheckDataTest3", "id int not null primary key auto_increment, test varchar(10)"); PreparedStatement stmt = sharedConnection.prepareStatement( "INSERT INTO CheckDataTest3 (test) VALUES (?)", Statement.RETURN_GENERATED_KEYS); @@ -172,7 +196,6 @@ public void testPrepareStatementExecuteAutoincrement() throws SQLException { @Test public void testPrepareStatementBatch() throws SQLException { - createTable("CheckDataTest4", "id int not null primary key auto_increment, test varchar(10)"); PreparedStatement stmt = sharedConnection.prepareStatement( "INSERT INTO CheckDataTest4 (test) VALUES (?)", Statement.RETURN_GENERATED_KEYS); diff --git a/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java b/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java index 21c824578..c72a2ee26 100644 --- a/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java +++ b/src/test/java/org/mariadb/jdbc/ClientPreparedStatementParsingTest.java @@ -163,7 +163,7 @@ public void testComment() throws Exception { + " tt VALUES " + "/* insert Select INSERT INTO tt VALUES (?,?,?,?) */" + " (", - ") " + "/* insert Select INSERT INTO tt VALUES (?,?,?,?) */" + ") /* insert Select INSERT INTO tt VALUES (?,?,?,?) */" })); } diff --git a/src/test/java/org/mariadb/jdbc/CollationTest.java b/src/test/java/org/mariadb/jdbc/CollationTest.java index 4826137a8..610f43e40 100644 --- a/src/test/java/org/mariadb/jdbc/CollationTest.java +++ b/src/test/java/org/mariadb/jdbc/CollationTest.java @@ -59,28 +59,36 @@ import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.Locale; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class CollationTest extends BaseTest { - - /** - * Tables Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "emojiTest", - "id int unsigned, field longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); - createTable( - "unicodeTestChar", - "id int unsigned, field1 varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, field2 longtext " - + "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", - "DEFAULT CHARSET=utf8mb4"); - createTable("textUtf8", "column1 text", "DEFAULT CHARSET=utf8"); - createTable("blobUtf8", "column1 blob", "DEFAULT CHARSET=utf8"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE emojiTest(id int unsigned, field longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci)"); + stmt.execute( + "CREATE TABLE unicodeTestChar(id int unsigned, field1 varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, field2 longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci) DEFAULT CHARSET=utf8mb4"); + stmt.execute("CREATE TABLE textUtf8(column1 text) DEFAULT CHARSET=utf8"); + stmt.execute("CREATE TABLE blobUtf8(column1 blob) DEFAULT CHARSET=utf8"); + stmt.execute("CREATE TABLE fooLatin1(x longtext) DEFAULT CHARSET=latin1"); + stmt.execute("CREATE TABLE languageCasing(ID int, id2 int)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE emojiTest"); + stmt.execute("DROP TABLE unicodeTestChar"); + stmt.execute("DROP TABLE textUtf8"); + stmt.execute("DROP TABLE blobUtf8"); + stmt.execute("DROP TABLE fooLatin1"); + stmt.execute("DROP TABLE languageCasing"); + } } /** @@ -216,8 +224,6 @@ public void testBinary() throws SQLException { */ @Test public void insertAndSelectShouldBothUseLatin1Encoding() throws SQLException { - createTable("fooLatin1", "x longtext", "DEFAULT CHARSET=latin1"); - // German Umlaute (ÄÖÜ) U+00C4, U+00D6, U+00DC final String latin1String = "ÄÖÜ"; @@ -251,7 +257,6 @@ public void insertAndSelectShouldBothUseLatin1Encoding() throws SQLException { @Test public void languageCasing() throws SQLException { Locale currentLocal = Locale.getDefault(); - createTable("languageCasing", "ID int, id2 int"); try (Statement statement = sharedConnection.createStatement()) { statement.execute("INSERT INTO languageCasing values (1,2)"); diff --git a/src/test/java/org/mariadb/jdbc/ComMultiPrepareStatementTest.java b/src/test/java/org/mariadb/jdbc/ComMultiPrepareStatementTest.java index 23a4f1516..f7622a958 100644 --- a/src/test/java/org/mariadb/jdbc/ComMultiPrepareStatementTest.java +++ b/src/test/java/org/mariadb/jdbc/ComMultiPrepareStatementTest.java @@ -53,13 +53,30 @@ package org.mariadb.jdbc; import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import org.junit.AfterClass; +import org.junit.BeforeClass; public class ComMultiPrepareStatementTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE test_insert_select_com_multi(`field1` varchar(20))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE test_insert_select_com_multi"); + } + } @org.junit.Test public void insertSelectTempTable2() throws Exception { requireMinimumVersion(10, 2); - createTable("test_insert_select_com_multi", "`field1` varchar(20)"); // prepare doesn't work. PreparedStatement stmt = sharedConnection.prepareStatement( diff --git a/src/test/java/org/mariadb/jdbc/ConnectionTest.java b/src/test/java/org/mariadb/jdbc/ConnectionTest.java index ae96348c2..1ee567ead 100644 --- a/src/test/java/org/mariadb/jdbc/ConnectionTest.java +++ b/src/test/java/org/mariadb/jdbc/ConnectionTest.java @@ -65,14 +65,22 @@ public class ConnectionTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("dummy", "a BLOB"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE dummy(a BLOB)"); + stmt.execute("CREATE DATABASE gogogo"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS dummy"); + stmt.execute("DROP DATABASE IF EXISTS gogogo"); + } } /** Conj-166. Connection error code must be thrown */ @@ -429,7 +437,6 @@ public void retrieveCatalogTest() throws SQLException { final String db = sharedConnection.getCatalog(); Statement stmt = sharedConnection.createStatement(); - stmt.execute("CREATE DATABASE gogogo"); stmt.execute("USE gogogo"); String db2 = sharedConnection.getCatalog(); assertEquals("gogogo", db2); @@ -583,7 +590,9 @@ public void run() { @Test public void verificationEd25519AuthPlugin() throws Throwable { Assume.assumeTrue( - System.getenv("MAXSCALE_TEST_DISABLE") == null && System.getenv("SKYSQL") == null); + System.getenv("MAXSCALE_TEST_DISABLE") == null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(isMariadbServer() && minVersion(10, 2)); Statement stmt = sharedConnection.createStatement(); @@ -677,7 +686,7 @@ private void checkConnection(String conUrl, int min, int max) { @Test public void replicaDownConnection() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); String url = "jdbc:mariadb:replication://" + hostname @@ -709,7 +718,9 @@ public void replicaDownConnection() throws SQLException { @Test public void multiAuthPlugin() throws Throwable { Assume.assumeTrue( - System.getenv("MAXSCALE_TEST_DISABLE") == null && System.getenv("SKYSQL") == null); + System.getenv("MAXSCALE_TEST_DISABLE") == null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(isMariadbServer() && minVersion(10, 4, 2)); Statement stmt = sharedConnection.createStatement(); try { @@ -767,7 +778,7 @@ public void quoteIdentifier() { @Test public void connectionUnexpectedClose() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); try (Connection connection = DriverManager.getConnection( "jdbc:mariadb:failover//" @@ -822,7 +833,7 @@ public void nativeSql() throws SQLException { @Test public void setReadonlyError() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); try (Connection connection = DriverManager.getConnection( "jdbc:mariadb:replication://" @@ -919,7 +930,9 @@ public void unwrapp() throws Throwable { @Test public void setClientNotConnectError() throws SQLException { Assume.assumeTrue( - System.getenv("MAXSCALE_TEST_DISABLE") == null && System.getenv("SKYSQL") == null); + System.getenv("MAXSCALE_TEST_DISABLE") == null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); // only mariadb return a specific error when connection has explicitly been killed Assume.assumeTrue(isMariadbServer()); @@ -988,6 +1001,7 @@ public void testNetworkTimeoutError() throws SQLException { public void readOnly() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("CREATE TABLE testReadOnly(id int)"); + stmt.execute("FLUSH TABLES"); sharedConnection.setAutoCommit(false); sharedConnection.setReadOnly(true); diff --git a/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java b/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java index 337c95fc1..a11fec72a 100644 --- a/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java +++ b/src/test/java/org/mariadb/jdbc/CredentialPluginTest.java @@ -22,10 +22,7 @@ package org.mariadb.jdbc; import java.sql.*; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class CredentialPluginTest extends BaseTest { @@ -102,6 +99,7 @@ public void propertiesIdentityTest() throws SQLException { @Test public void specificPropertiesIdentityTest() throws SQLException { + System.setProperty("myUserKey", "identityUser"); System.setProperty("myPwdKey", "!Passw0rd3Works"); @@ -114,7 +112,11 @@ public void specificPropertiesIdentityTest() throws SQLException { + "/" + ((database == null) ? "" : database) + "?credentialType=PROPERTY" - + "&userKey=myUserKey&pwdKey=myPwdKey")) { + + "&userKey=myUserKey&pwdKey=myPwdKey" + + ((options.useSsl != null) ? "&useSsl=" + options.useSsl : "") + + ((options.serverSslCert != null) + ? "&serverSslCert=" + options.serverSslCert + : ""))) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT '5'"); diff --git a/src/test/java/org/mariadb/jdbc/DataNTypeTest.java b/src/test/java/org/mariadb/jdbc/DataNTypeTest.java index 5233146bd..58b7a5f97 100644 --- a/src/test/java/org/mariadb/jdbc/DataNTypeTest.java +++ b/src/test/java/org/mariadb/jdbc/DataNTypeTest.java @@ -57,19 +57,47 @@ import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.Types; +import java.sql.*; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; @SuppressWarnings("ALL") public class DataNTypeTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE testSetNClob(id int not null primary key, strm text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE testSetObjectNClob(id int not null primary key, strm text, strm2 text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE testSetNString(id int not null primary key, strm varchar(10)) CHARSET utf8"); + stmt.execute( + "CREATE TABLE testSetObjectNString(id int not null primary key, strm varchar(10), strm2 varchar(10)) CHARSET utf8"); + stmt.execute( + "CREATE TABLE testSetNCharacter(id int not null primary key, strm text) CHARSET utf8"); + stmt.execute( + "CREATE TABLE testSetObjectNCharacter(id int not null primary key, strm text) CHARSET utf8"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE testSetNClob"); + stmt.execute("DROP TABLE testSetObjectNClob"); + stmt.execute("DROP TABLE testSetNString"); + stmt.execute("DROP TABLE testSetObjectNString"); + stmt.execute("DROP TABLE testSetNCharacter"); + stmt.execute("DROP TABLE testSetObjectNCharacter"); + } + } + @Test public void testSetNClob() throws Exception { - - createTable("testSetNClob", "id int not null primary key, strm text", "CHARSET utf8"); PreparedStatement stmt = sharedConnection.prepareStatement("insert into testSetNClob (id, strm) values (?,?)"); NClob nclob = sharedConnection.createNClob(); @@ -92,9 +120,6 @@ public void testSetNClob() throws Exception { @Test public void testSetObjectNClob() throws Exception { - - createTable( - "testSetObjectNClob", "id int not null primary key, strm text, strm2 text", "CHARSET utf8"); PreparedStatement stmt = sharedConnection.prepareStatement( "insert into testSetObjectNClob (id, strm, strm2) values (?,?,?)"); @@ -122,7 +147,6 @@ public void testSetObjectNClob() throws Exception { @Test public void testSetNString() throws Exception { - createTable("testSetNString", "id int not null primary key, strm varchar(10)", "CHARSET utf8"); PreparedStatement stmt = sharedConnection.prepareStatement("insert into testSetNString (id, strm) values (?,?)"); stmt.setInt(1, 1); @@ -137,11 +161,6 @@ public void testSetNString() throws Exception { @Test public void testSetObjectNString() throws Exception { - - createTable( - "testSetObjectNString", - "id int not null primary key, strm varchar(10), strm2 varchar(10)", - "CHARSET utf8"); PreparedStatement stmt = sharedConnection.prepareStatement( "insert into testSetObjectNString (id, strm, strm2) values (?, ?, ?)"); @@ -163,8 +182,6 @@ public void testSetObjectNString() throws Exception { @Test public void testSetNCharacter() throws Exception { - - createTable("testSetNCharacter", "id int not null primary key, strm text", "CHARSET utf8"); PreparedStatement stmt = sharedConnection.prepareStatement("insert into testSetNCharacter (id, strm) values (?,?)"); String toInsert = "Øabcdefgh\njklmn\""; @@ -190,9 +207,6 @@ public void testSetNCharacter() throws Exception { @Test public void testSetObjectNCharacter() throws Exception { - - createTable( - "testSetObjectNCharacter", "id int not null primary key, strm text", "CHARSET utf8"); PreparedStatement stmt = sharedConnection.prepareStatement( "insert into testSetObjectNCharacter (id, strm) values (?,?)"); diff --git a/src/test/java/org/mariadb/jdbc/DataSourcePoolTest.java b/src/test/java/org/mariadb/jdbc/DataSourcePoolTest.java index d3ff218d1..802964a0d 100644 --- a/src/test/java/org/mariadb/jdbc/DataSourcePoolTest.java +++ b/src/test/java/org/mariadb/jdbc/DataSourcePoolTest.java @@ -39,7 +39,7 @@ public class DataSourcePoolTest extends BaseTest { /** Initialisation. */ @BeforeClass public static void beforeClassDataSourceTest() { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); connectToIP = System.getProperty("testConnectToIP", defConnectToIP); } @@ -113,7 +113,7 @@ public void testDataSourcePool() throws SQLException { */ @Test public void setDatabaseNameTest() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); try (MariaDbPoolDataSource ds = new MariaDbPoolDataSource(hostname == null ? "localhost" : hostname, port, database)) { try (Connection connection = ds.getConnection(username, password)) { @@ -127,6 +127,8 @@ public void setDatabaseNameTest() throws SQLException { .contains("can not perform a configuration change once initialized")); } } + } finally { + sharedConnection.createStatement().execute("DROP DATABASE IF EXISTS test2"); } } diff --git a/src/test/java/org/mariadb/jdbc/DataSourceTest.java b/src/test/java/org/mariadb/jdbc/DataSourceTest.java index 8b05056b2..f900efa8a 100644 --- a/src/test/java/org/mariadb/jdbc/DataSourceTest.java +++ b/src/test/java/org/mariadb/jdbc/DataSourceTest.java @@ -58,6 +58,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -67,6 +68,22 @@ public class DataSourceTest extends BaseTest { protected static final String defConnectToIP = null; protected static String connectToIP; + @BeforeClass() + public static void initClass() throws SQLException { + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE DATABASE test2"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP DATABASE IF EXISTS test2"); + } + } + /** Initialisation. */ @BeforeClass public static void beforeClassDataSourceTest() { @@ -152,17 +169,18 @@ public void testDataSourceTimeout4() throws SQLException { @Test public void setDatabaseNameTest() throws SQLException { Assume.assumeFalse(options.useSsl != null && options.useSsl); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue( + System.getenv("MAXSCALE_TEST_DISABLE") == null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); try (Connection connection = ds.getConnection(username, password)) { - connection.createStatement().execute("CREATE DATABASE IF NOT EXISTS test2"); ds.setDatabaseName("test2"); try (Connection connection2 = ds.getConnection(username, password)) { assertEquals("test2", ds.getDatabaseName()); assertEquals(ds.getDatabaseName(), connection2.getCatalog()); - connection2.createStatement().execute("DROP DATABASE IF EXISTS test2"); } } } diff --git a/src/test/java/org/mariadb/jdbc/DataTypeSignedTest.java b/src/test/java/org/mariadb/jdbc/DataTypeSignedTest.java index 24efed3b9..66c9cd7e7 100644 --- a/src/test/java/org/mariadb/jdbc/DataTypeSignedTest.java +++ b/src/test/java/org/mariadb/jdbc/DataTypeSignedTest.java @@ -58,24 +58,35 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class DataTypeSignedTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("signedTinyIntTest", "id TINYINT"); - createTable("signedSmallIntTest", "id SMALLINT"); - createTable("signedMediumIntTest", "id MEDIUMINT"); - createTable("signedIntTest", "id INT"); - createTable("signedBigIntTest", "id BIGINT"); - createTable("signedDecimalTest", "id DECIMAL(65,20)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE signedTinyIntTest(id TINYINT)"); + stmt.execute("CREATE TABLE signedSmallIntTest(id SMALLINT)"); + stmt.execute("CREATE TABLE signedMediumIntTest(id MEDIUMINT)"); + stmt.execute("CREATE TABLE signedIntTest(id INT)"); + stmt.execute("CREATE TABLE signedBigIntTest(id BIGINT)"); + stmt.execute("CREATE TABLE signedDecimalTest(id DECIMAL(65,20))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS signedTinyIntTest"); + stmt.execute("DROP TABLE IF EXISTS signedSmallIntTest"); + stmt.execute("DROP TABLE IF EXISTS signedMediumIntTest"); + stmt.execute("DROP TABLE IF EXISTS signedIntTest"); + stmt.execute("DROP TABLE IF EXISTS signedBigIntTest"); + stmt.execute("DROP TABLE IF EXISTS signedDecimalTest"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/DataTypeUnsignedTest.java b/src/test/java/org/mariadb/jdbc/DataTypeUnsignedTest.java index 5852ca27f..2becd62b3 100644 --- a/src/test/java/org/mariadb/jdbc/DataTypeUnsignedTest.java +++ b/src/test/java/org/mariadb/jdbc/DataTypeUnsignedTest.java @@ -59,28 +59,44 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class DataTypeUnsignedTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("unsignedBitTest", "id BIT(8)"); - createTable("unsignedTinyIntTest", "id TINYINT UNSIGNED"); - createTable("unsignedSmallIntTest", "id SMALLINT UNSIGNED"); - createTable("yearTest", "id YEAR(4) "); - createTable("unsignedMediumIntTest", "id MEDIUMINT UNSIGNED"); - createTable("unsignedIntTest", "id INT UNSIGNED"); - createTable("unsignedBigIntTest", "id BIGINT UNSIGNED"); - createTable("unsignedDecimalTest", "id DECIMAL(65,20) UNSIGNED"); - createTable("unsignedFloatTest", "id FLOAT UNSIGNED"); - createTable("unsignedDoubleTest", "id DOUBLE UNSIGNED"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE unsignedBitTest(id BIT(8))"); + stmt.execute("CREATE TABLE unsignedTinyIntTest(id TINYINT UNSIGNED)"); + stmt.execute("CREATE TABLE unsignedSmallIntTest(id SMALLINT UNSIGNED)"); + stmt.execute("CREATE TABLE yearTest(id YEAR(4))"); + stmt.execute("CREATE TABLE unsignedMediumIntTest(id MEDIUMINT UNSIGNED)"); + stmt.execute("CREATE TABLE unsignedIntTest(id INT UNSIGNED)"); + stmt.execute("CREATE TABLE unsignedBigIntTest(id BIGINT UNSIGNED)"); + stmt.execute("CREATE TABLE unsignedDecimalTest(id DECIMAL(65,20) UNSIGNED)"); + stmt.execute("CREATE TABLE unsignedFloatTest(id FLOAT UNSIGNED)"); + stmt.execute("CREATE TABLE unsignedDoubleTest(id DOUBLE UNSIGNED)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS unsignedBitTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedTinyIntTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedSmallIntTest"); + stmt.execute("DROP TABLE IF EXISTS yearTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedMediumIntTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedIntTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedBigIntTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedDecimalTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedFloatTest"); + stmt.execute("DROP TABLE IF EXISTS unsignedDoubleTest"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/DatabaseMetadataTest.java b/src/test/java/org/mariadb/jdbc/DatabaseMetadataTest.java index bac2e6672..be98c204a 100644 --- a/src/test/java/org/mariadb/jdbc/DatabaseMetadataTest.java +++ b/src/test/java/org/mariadb/jdbc/DatabaseMetadataTest.java @@ -59,92 +59,151 @@ public class DatabaseMetadataTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "dbpk_test", - "val varchar(20), id1 int not null, id2 int not null,primary key(id1, id2)", - "engine=innodb"); - createTable("datetime_test", "dt datetime"); - createTable( - "`manycols`", - " `tiny` tinyint(4) DEFAULT NULL," - + " `tiny_uns` tinyint(3) unsigned DEFAULT NULL," - + " `small` smallint(6) DEFAULT NULL," - + " `small_uns` smallint(5) unsigned DEFAULT NULL," - + " `medium` mediumint(9) DEFAULT NULL," - + " `medium_uns` mediumint(8) unsigned DEFAULT NULL," - + " `int_col` int(11) DEFAULT NULL," - + " `int_col_uns` int(10) unsigned DEFAULT NULL," - + " `big` bigint(20) DEFAULT NULL," - + " `big_uns` bigint(20) unsigned DEFAULT NULL," - + " `decimal_col` decimal(10,5) DEFAULT NULL," - + " `fcol` float DEFAULT NULL," - + " `fcol_uns` float unsigned DEFAULT NULL," - + " `dcol` double DEFAULT NULL," - + " `dcol_uns` double unsigned DEFAULT NULL," - + " `date_col` date DEFAULT NULL," - + " `time_col` time DEFAULT NULL," - + " `timestamp_col` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," - + " `year_col` year(4) DEFAULT NULL," - + " `bit_col` bit(5) DEFAULT NULL," - + " `char_col` char(5) DEFAULT NULL," - + " `varchar_col` varchar(10) DEFAULT NULL," - + " `binary_col` binary(10) DEFAULT NULL," - + " `varbinary_col` varbinary(10) DEFAULT NULL," - + " `tinyblob_col` tinyblob," - + " `blob_col` blob," - + " `mediumblob_col` mediumblob," - + " `longblob_col` longblob," - + " `tinytext_col` tinytext," - + " `text_col` text," - + " `mediumtext_col` mediumtext," - + " `longtext_col` longtext"); - createTable("ytab", "y year"); - createTable("maxcharlength", "maxcharlength char(1)", "character set utf8"); - createTable("conj72", "t tinyint(1)"); - if (isMariadbServer() && minVersion(10, 3, 4)) { - createTable("versionTable", "x INT", "WITH SYSTEM VERSIONING"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE dbpk_test(val varchar(20), id1 int not null, id2 int not null,primary key(id1, id2)) engine=innodb"); + stmt.execute("CREATE TABLE datetime_test(dt datetime)"); + stmt.execute( + "CREATE TABLE `manycols`(" + + " `tiny` tinyint(4) DEFAULT NULL," + + " `tiny_uns` tinyint(3) unsigned DEFAULT NULL," + + " `small` smallint(6) DEFAULT NULL," + + " `small_uns` smallint(5) unsigned DEFAULT NULL," + + " `medium` mediumint(9) DEFAULT NULL," + + " `medium_uns` mediumint(8) unsigned DEFAULT NULL," + + " `int_col` int(11) DEFAULT NULL," + + " `int_col_uns` int(10) unsigned DEFAULT NULL," + + " `big` bigint(20) DEFAULT NULL," + + " `big_uns` bigint(20) unsigned DEFAULT NULL," + + " `decimal_col` decimal(10,5) DEFAULT NULL," + + " `fcol` float DEFAULT NULL," + + " `fcol_uns` float unsigned DEFAULT NULL," + + " `dcol` double DEFAULT NULL," + + " `dcol_uns` double unsigned DEFAULT NULL," + + " `date_col` date DEFAULT NULL," + + " `time_col` time DEFAULT NULL," + + " `timestamp_col` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + + " `year_col` year(4) DEFAULT NULL," + + " `bit_col` bit(5) DEFAULT NULL," + + " `char_col` char(5) DEFAULT NULL," + + " `varchar_col` varchar(10) DEFAULT NULL," + + " `binary_col` binary(10) DEFAULT NULL," + + " `varbinary_col` varbinary(10) DEFAULT NULL," + + " `tinyblob_col` tinyblob," + + " `blob_col` blob," + + " `mediumblob_col` mediumblob," + + " `longblob_col` longblob," + + " `tinytext_col` tinytext," + + " `text_col` text," + + " `mediumtext_col` mediumtext," + + " `longtext_col` longtext)"); + stmt.execute("CREATE TABLE ytab(y year)"); + stmt.execute("CREATE TABLE maxcharlength(maxcharlength char(1)) character set utf8"); + stmt.execute("CREATE TABLE conj72(t tinyint(1))"); + if (isMariadbServer() && minVersion(10, 3, 4)) { + stmt.execute("CREATE TABLE versionTable(x INT) WITH SYSTEM VERSIONING"); + } + stmt.execute("create table cross1 (id int not null primary key, val varchar(20))"); + stmt.execute( + "create table cross2 (id int not null, id2 int not null, " + + "id_ref0 int, foreign key (id_ref0) references cross1(id), UNIQUE unik_name (id, id2))"); + stmt.execute( + "create table cross3 (id int not null primary key, " + + "id_ref1 int, id_ref2 int, foreign key fk_my_name (id_ref1, id_ref2) references cross2(id, id2) on " + + "update cascade)"); + stmt.execute( + "create table getBestRowIdentifier1(i int not null primary key auto_increment, id int, " + + "id_ref1 int, id_ref2 int, foreign key fk_my_name_1 (id_ref1, id_ref2) references cross2(id, id2) on " + + "update cascade, UNIQUE getBestRowIdentifier_unik (id))"); + stmt.execute( + "create table getBestRowIdentifier2(id_ref0 int not null, " + + "id_ref1 int, id_ref2 int not null, UNIQUE (id_ref1, id_ref2) , UNIQUE (id_ref0, id_ref2))"); + stmt.execute( + "CREATE TABLE getPrecision(" + + "num1 NUMERIC(9,4), " + + "num2 NUMERIC (9,0)," + + "num3 NUMERIC (9,4) UNSIGNED," + + "num4 NUMERIC (9,0) UNSIGNED," + + "num5 FLOAT(9,4)," + + "num6 FLOAT(9,4) UNSIGNED," + + "num7 DOUBLE(9,4)," + + "num8 DOUBLE(9,4) UNSIGNED)"); + stmt.execute( + "CREATE TABLE getTimePrecision(" + + "d date, " + + "t1 datetime(0)," + + "t2 datetime(6)," + + "t3 timestamp(0) DEFAULT '2000-01-01 00:00:00'," + + "t4 timestamp(6) DEFAULT '2000-01-01 00:00:00'," + + "t5 time(0)," + + "t6 time(6))"); + stmt.execute( + "CREATE TABLE getTimePrecision2(" + + "d date, " + + "t1 datetime(0)," + + "t2 datetime(6)," + + "t3 timestamp(0) DEFAULT '2000-01-01 00:00:00'," + + "t4 timestamp(6) DEFAULT '2000-01-01 00:00:00'," + + "t5 time(0)," + + "t6 time(6))"); + + stmt.execute( + "CREATE PROCEDURE getProcTimePrecision2(IN I date, " + + "IN t1 DATETIME," + + "IN t3 timestamp," + + "IN t5 time) BEGIN SELECT I; END"); + stmt.execute( + "CREATE PROCEDURE getProcTimePrecision(IN I date, " + + "IN t1 DATETIME(0)," + + "IN t2 DATETIME(6)," + + "IN t3 timestamp(0)," + + "IN t4 timestamp(6)," + + "IN t5 time ," + + "IN t6 time(6)) BEGIN SELECT I; END"); + stmt.execute( + "create table prim_key (id int not null primary key, val varchar(20)) engine=innodb"); + stmt.execute( + "create table fore_key0 (id int not null primary key, " + + "id_ref0 int, foreign key (id_ref0) references prim_key(id)) engine=innodb"); + stmt.execute( + "create table fore_key1 (id int not null primary key, " + + "id_ref1 int, foreign key (id_ref1) references prim_key(id) on update cascade) engine=innodb"); + stmt.execute( + "create table table_type_test (id int not null primary key, " + + "val varchar(20)) engine=innodb"); + stmt.execute("FLUSH TABLES"); } - Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists cross3"); - stmt.execute("drop table if exists cross2"); - stmt.execute("drop table if exists cross1"); - stmt.execute("create table cross1 (id int not null primary key, val varchar(20))"); - stmt.execute( - "create table cross2 (id int not null, id2 int not null, " - + "id_ref0 int, foreign key (id_ref0) references cross1(id), UNIQUE unik_name (id, id2))"); - stmt.execute( - "create table cross3 (id int not null primary key, " - + "id_ref1 int, id_ref2 int, foreign key fk_my_name (id_ref1, id_ref2) references cross2(id, id2) on " - + "update cascade)"); - stmt.execute( - "create table getBestRowIdentifier1(i int not null primary key auto_increment, id int, " - + "id_ref1 int, id_ref2 int, foreign key fk_my_name_1 (id_ref1, id_ref2) references cross2(id, id2) on " - + "update cascade, UNIQUE getBestRowIdentifier_unik (id))"); - stmt.execute( - "create table getBestRowIdentifier2(id_ref0 int not null, " - + "id_ref1 int, id_ref2 int not null, UNIQUE (id_ref1, id_ref2) , UNIQUE (id_ref0, id_ref2))"); } - /** - * Initialisation. - * - * @throws SQLException exception - */ @AfterClass public static void afterClass() throws SQLException { - Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists getBestRowIdentifier1"); - stmt.execute("drop table if exists getBestRowIdentifier2"); - stmt.execute("drop table if exists cross3"); - stmt.execute("drop table if exists cross2"); - stmt.execute("drop table if exists cross1"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS dbpk_test"); + stmt.execute("DROP TABLE IF EXISTS datetime_test"); + stmt.execute("DROP TABLE IF EXISTS `manycols`"); + stmt.execute("DROP TABLE IF EXISTS ytab"); + stmt.execute("DROP TABLE IF EXISTS maxcharlength"); + stmt.execute("DROP TABLE IF EXISTS conj72"); + stmt.execute("DROP TABLE IF EXISTS versionTable"); + stmt.execute("drop table if exists getBestRowIdentifier1"); + stmt.execute("drop table if exists getBestRowIdentifier2"); + stmt.execute("drop table if exists cross3"); + stmt.execute("drop table if exists cross2"); + stmt.execute("drop table if exists cross1"); + stmt.execute("drop table if exists getPrecision"); + stmt.execute("drop table if exists tablegetcolumns"); + stmt.execute("drop table if exists getTimePrecision"); + stmt.execute("drop table if exists getTimePrecision2"); + stmt.execute("drop procedure if exists getProcTimePrecision"); + stmt.execute("drop procedure if exists getProcTimePrecision2"); + stmt.execute("drop table if exists fore_key0"); + stmt.execute("drop table if exists fore_key1"); + stmt.execute("drop table if exists prim_key"); + stmt.execute("drop table if exists table_type_test"); + } } private static void checkType(String name, int actualType, String colName, int expectedType) { @@ -185,7 +244,7 @@ public void primaryKeyTest2() throws SQLException { "CREATE TABLE t2 (id2a integer, id2b integer, constraint pk primary key(id2a, id2b), " + "constraint fk1 foreign key(id2a) references t1(id1), constraint fk2 foreign key(id2b) " + "references t1(id1))"); - + stmt.execute("FLUSH TABLES"); DatabaseMetaData dbmd = sharedConnection.getMetaData(); ResultSet rs = dbmd.getPrimaryKeys("testj", null, "t2"); int counter = 0; @@ -285,7 +344,7 @@ public void getImportedKeys() throws Exception { + " FOREIGN KEY (customer_id)\n" + " REFERENCES `cus``tomer`(id)\n" + ") ENGINE=INNODB;"); - + st.execute("FLUSH TABLES"); /* Test that I_S implementation is equivalent to parsing "show create table" . Get result sets using either method and compare (ignore minor differences INT vs SMALLINT @@ -442,18 +501,6 @@ public void exportedKeysTest() throws SQLException { @Test public void importedKeysTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists fore_key0"); - stmt.execute("drop table if exists fore_key1"); - stmt.execute("drop table if exists prim_key"); - - stmt.execute( - "create table prim_key (id int not null primary key, " + "val varchar(20)) engine=innodb"); - stmt.execute( - "create table fore_key0 (id int not null primary key, " - + "id_ref0 int, foreign key (id_ref0) references prim_key(id)) engine=innodb"); - stmt.execute( - "create table fore_key1 (id int not null primary key, " - + "id_ref1 int, foreign key (id_ref1) references prim_key(id) on update cascade) engine=innodb"); DatabaseMetaData dbmd = sharedConnection.getMetaData(); ResultSet rs = dbmd.getImportedKeys(sharedConnection.getCatalog(), null, "fore_key0"); @@ -464,9 +511,6 @@ public void importedKeysTest() throws SQLException { counter++; } assertEquals(1, counter); - stmt.execute("drop table if exists fore_key0"); - stmt.execute("drop table if exists fore_key1"); - stmt.execute("drop table if exists prim_key"); } @Test @@ -492,19 +536,6 @@ public void testGetCatalogs() throws SQLException { @Test public void testGetTables() throws SQLException { Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists fore_key0"); - stmt.execute("drop table if exists fore_key1"); - stmt.execute("drop table if exists prim_key"); - - stmt.execute( - "create table prim_key (id int not null primary key, " + "val varchar(20)) engine=innodb"); - stmt.execute( - "create table fore_key0 (id int not null primary key, " - + "id_ref0 int, foreign key (id_ref0) references prim_key(id)) engine=innodb"); - stmt.execute( - "create table fore_key1 (id int not null primary key, " - + "id_ref1 int, foreign key (id_ref1) references prim_key(id) on update cascade) engine=innodb"); - DatabaseMetaData dbmd = sharedConnection.getMetaData(); ResultSet rs = dbmd.getTables(null, null, "prim_key", null); @@ -542,12 +573,6 @@ public void testGetTablesSystemVersionTables() throws SQLException { @Test public void testGetTables3() throws SQLException { Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists table_type_test"); - - stmt.execute( - "create table table_type_test (id int not null primary key, " - + "val varchar(20)) engine=innodb"); - DatabaseMetaData dbmd = sharedConnection.getMetaData(); ResultSet tableSet = dbmd.getTables(null, null, "table_type_test", null); @@ -566,19 +591,19 @@ public void testGetTables3() throws SQLException { public void testGetColumns() throws SQLException { // mysql 5.6 doesn't permit VIRTUAL keyword Assume.assumeTrue(isMariadbServer() || !isMariadbServer() && minVersion(5, 7)); - - if (minVersion(10, 2) || !isMariadbServer()) { - createTable( - "tablegetcolumns", - "a INT NOT NULL primary key auto_increment, b VARCHAR(32), c INT AS (CHAR_LENGTH(b)) VIRTUAL, " - + "d VARCHAR(5) AS (left(b,5)) STORED", - "CHARACTER SET 'utf8mb4'"); - } else { - createTable( - "tablegetcolumns", - "a INT NOT NULL primary key auto_increment, b VARCHAR(32), c INT AS (CHAR_LENGTH(b)) VIRTUAL, " - + "d VARCHAR(5) AS (left(b,5)) PERSISTENT", - "CHARACTER SET 'utf8mb4'"); + try (Statement stmt = sharedConnection.createStatement()) { + if (minVersion(10, 2) || !isMariadbServer()) { + stmt.execute( + "CREATE TABLE tablegetcolumns(" + + "a INT NOT NULL primary key auto_increment, b VARCHAR(32), c INT AS (CHAR_LENGTH(b)) VIRTUAL, " + + "d VARCHAR(5) AS (left(b,5)) STORED) CHARACTER SET 'utf8mb4'"); + } else { + stmt.execute( + "CREATE TABLE tablegetcolumns(" + + "a INT NOT NULL primary key auto_increment, b VARCHAR(32), c INT AS (CHAR_LENGTH(b)) VIRTUAL, " + + "d VARCHAR(5) AS (left(b,5)) PERSISTENT) CHARACTER SET 'utf8mb4'"); + } + stmt.execute("FLUSH TABLES"); } DatabaseMetaData dbmd = sharedConnection.getMetaData(); @@ -1373,16 +1398,6 @@ public void conj72() throws Exception { @Test public void getPrecision() throws SQLException { - createTable( - "getPrecision", - "num1 NUMERIC(9,4), " - + "num2 NUMERIC (9,0)," - + "num3 NUMERIC (9,4) UNSIGNED," - + "num4 NUMERIC (9,0) UNSIGNED," - + "num5 FLOAT(9,4)," - + "num6 FLOAT(9,4) UNSIGNED," - + "num7 DOUBLE(9,4)," - + "num8 DOUBLE(9,4) UNSIGNED"); Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM getPrecision"); ResultSetMetaData rsmd = rs.getMetaData(); @@ -1407,15 +1422,6 @@ public void getPrecision() throws SQLException { @Test public void getTimePrecision() throws SQLException { Assume.assumeTrue(doPrecisionTest); - createTable( - "getTimePrecision", - "d date, " - + "t1 datetime(0)," - + "t2 datetime(6)," - + "t3 timestamp(0) DEFAULT '2000-01-01 00:00:00'," - + "t4 timestamp(6) DEFAULT '2000-01-01 00:00:00'," - + "t5 time(0)," - + "t6 time(6)"); Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM getTimePrecision"); ResultSetMetaData rsmd = rs.getMetaData(); @@ -1445,20 +1451,11 @@ public void getTimePrecision() throws SQLException { @Test public void metaTimeResultSet() throws SQLException { Assume.assumeTrue(doPrecisionTest); - createTable( - "getTimePrecision", - "d date, " - + "t1 datetime(0)," - + "t2 datetime(6)," - + "t3 timestamp(0) DEFAULT '2000-01-01 00:00:00'," - + "t4 timestamp(6) DEFAULT '2000-01-01 00:00:00'," - + "t5 time(0)," - + "t6 time(6)"); final int columnSizeField = 7; DatabaseMetaData dmd = sharedConnection.getMetaData(); - ResultSet rs = dmd.getColumns(null, null, "getTimePrecision", null); + ResultSet rs = dmd.getColumns(null, null, "getTimePrecision2", null); // date assertTrue(rs.next()); assertEquals(10, rs.getInt(columnSizeField)); @@ -1491,12 +1488,6 @@ public void metaTimeResultSet() throws SQLException { */ @Test public void metaTimeNoPrecisionProcedureResultSet() throws SQLException { - createProcedure( - "getProcTimePrecision2", - "(IN I date, " - + "IN t1 DATETIME," - + "IN t3 timestamp," - + "IN t5 time) BEGIN SELECT I; END"); final int precisionField = 8; final int lengthField = 9; @@ -1537,15 +1528,6 @@ public void metaTimeNoPrecisionProcedureResultSet() throws SQLException { @Test public void metaTimeProcedureResultSet() throws SQLException { Assume.assumeTrue(doPrecisionTest); - createProcedure( - "getProcTimePrecision", - "(IN I date, " - + "IN t1 DATETIME(0)," - + "IN t2 DATETIME(6)," - + "IN t3 timestamp(0)," - + "IN t4 timestamp(6)," - + "IN t5 time ," - + "IN t6 time(6)) BEGIN SELECT I; END"); final int precisionField = 8; final int lengthField = 9; diff --git a/src/test/java/org/mariadb/jdbc/DatatypeCompatibilityTest.java b/src/test/java/org/mariadb/jdbc/DatatypeCompatibilityTest.java index ca703c84b..6be3b1ea3 100644 --- a/src/test/java/org/mariadb/jdbc/DatatypeCompatibilityTest.java +++ b/src/test/java/org/mariadb/jdbc/DatatypeCompatibilityTest.java @@ -58,6 +58,7 @@ import java.math.BigInteger; import java.sql.*; import java.util.Arrays; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -66,65 +67,70 @@ public class DatatypeCompatibilityTest extends BaseTest { private static final String sql = "SELECT id, time_test FROM time_test;"; - /** - * Initialization. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "pk_test", - "val varchar(20), id1 int not null, id2 int not null,primary key(id1, id2)", - "engine=innodb"); - createTable("datetime_test", "dt datetime"); - createTable( - "`manycols`", - " `tiny` tinyint(4) DEFAULT NULL,\n" - + " `tiny_uns` tinyint(3) unsigned DEFAULT NULL,\n" - + " `small` smallint(6) DEFAULT NULL,\n" - + " `small_uns` smallint(5) unsigned DEFAULT NULL,\n" - + " `medium` mediumint(9) DEFAULT NULL,\n" - + " `medium_uns` mediumint(8) unsigned DEFAULT NULL,\n" - + " `int_col` int(11) DEFAULT NULL,\n" - + " `int_col_uns` int(10) unsigned DEFAULT NULL,\n" - + " `big` bigint(20) DEFAULT NULL,\n" - + " `big_uns` bigint(20) unsigned DEFAULT NULL,\n" - + " `decimal_col` decimal(10,5) DEFAULT NULL,\n" - + " `fcol` float DEFAULT NULL,\n" - + " `fcol_uns` float unsigned DEFAULT NULL,\n" - + " `dcol` double DEFAULT NULL,\n" - + " `dcol_uns` double unsigned DEFAULT NULL,\n" - + " `date_col` date DEFAULT NULL,\n" - + " `time_col` time DEFAULT NULL,\n" - + " `timestamp_col` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE\n" - + "CURRENT_TIMESTAMP,\n" - + " `year_col` year(4) DEFAULT NULL,\n" - + " `bit_col` bit(5) DEFAULT NULL,\n" - + " `char_col` char(5) DEFAULT NULL,\n" - + " `varchar_col` varchar(10) DEFAULT NULL,\n" - + " `binary_col` binary(10) DEFAULT NULL,\n" - + " `varbinary_col` varbinary(10) DEFAULT NULL,\n" - + " `tinyblob_col` tinyblob,\n" - + " `blob_col` blob,\n" - + " `mediumblob_col` mediumblob,\n" - + " `longblob_col` longblob,\n" - + " `text_col` text,\n" - + " `mediumtext_col` mediumtext,\n" - + " `longtext_col` longtext"); - createTable("ytab", "y year"); - createTable("maxcharlength", "maxcharlength char(1)", "character set utf8"); - if (doPrecisionTest) { - createTable( - "time_test", - "ID int unsigned NOT NULL, time_test time(6), PRIMARY KEY (ID)", - "engine=InnoDB"); - if (testSingleHost) { - sharedConnection - .createStatement() - .execute( - "insert into time_test(id, time_test) values(1, '00:00:00'), (2, '00:00:00.123'), (3, null)"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE pk_test(val varchar(20), id1 int not null, id2 int not null,primary key(id1, id2))"); + stmt.execute("CREATE TABLE datetime_test(dt datetime)"); + stmt.execute( + "CREATE TABLE `manycols`(" + + " `tiny` tinyint(4) DEFAULT NULL,\n" + + " `tiny_uns` tinyint(3) unsigned DEFAULT NULL,\n" + + " `small` smallint(6) DEFAULT NULL,\n" + + " `small_uns` smallint(5) unsigned DEFAULT NULL,\n" + + " `medium` mediumint(9) DEFAULT NULL,\n" + + " `medium_uns` mediumint(8) unsigned DEFAULT NULL,\n" + + " `int_col` int(11) DEFAULT NULL,\n" + + " `int_col_uns` int(10) unsigned DEFAULT NULL,\n" + + " `big` bigint(20) DEFAULT NULL,\n" + + " `big_uns` bigint(20) unsigned DEFAULT NULL,\n" + + " `decimal_col` decimal(10,5) DEFAULT NULL,\n" + + " `fcol` float DEFAULT NULL,\n" + + " `fcol_uns` float unsigned DEFAULT NULL,\n" + + " `dcol` double DEFAULT NULL,\n" + + " `dcol_uns` double unsigned DEFAULT NULL,\n" + + " `date_col` date DEFAULT NULL,\n" + + " `time_col` time DEFAULT NULL,\n" + + " `timestamp_col` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE\n" + + "CURRENT_TIMESTAMP,\n" + + " `year_col` year(4) DEFAULT NULL,\n" + + " `bit_col` bit(5) DEFAULT NULL,\n" + + " `char_col` char(5) DEFAULT NULL,\n" + + " `varchar_col` varchar(10) DEFAULT NULL,\n" + + " `binary_col` binary(10) DEFAULT NULL,\n" + + " `varbinary_col` varbinary(10) DEFAULT NULL,\n" + + " `tinyblob_col` tinyblob,\n" + + " `blob_col` blob,\n" + + " `mediumblob_col` mediumblob,\n" + + " `longblob_col` longblob,\n" + + " `text_col` text,\n" + + " `mediumtext_col` mediumtext,\n" + + " `longtext_col` longtext)"); + stmt.execute("CREATE TABLE ytab(y year)"); + stmt.execute("CREATE TABLE maxcharlength(maxcharlength char(1)) character set utf8"); + if (doPrecisionTest) { + stmt.execute( + "CREATE TABLE time_test(ID int unsigned NOT NULL, time_test time(6), PRIMARY KEY (ID))"); + if (testSingleHost) { + stmt.execute( + "insert into time_test(id, time_test) values(1, '00:00:00'), (2, '00:00:00.123'), (3, null)"); + } } + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS pk_test"); + stmt.execute("DROP TABLE IF EXISTS datetime_test"); + stmt.execute("DROP TABLE IF EXISTS `manycols`"); + stmt.execute("DROP TABLE IF EXISTS ytab"); + stmt.execute("DROP TABLE IF EXISTS maxcharlength"); + stmt.execute("DROP TABLE IF EXISTS time_test"); } } @@ -212,7 +218,7 @@ public void testBitTypes() throws SQLException { "BIT(64)", byte[].class, Types.VARBINARY, - "b'1111111111111111111111111111111111111111111111111111" + "111111111111'", + "b'1111111111111111111111111111111111111111111111111111111111111111'", new byte[] {-1, -1, -1, -1, -1, -1, -1, -1}); } @@ -225,13 +231,15 @@ private void assertType( throws SQLException { assertNotNull(expectedObjectValue); assertSame("bad test spec: ", expectedClass, expectedObjectValue.getClass()); + String columnName = + columnType.replace(" ", "_").replace("(", "_").replace(")", "").replace(",", "_"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE my_table_" + columnName + "(my_col " + columnType + ")"); + stmt.execute("FLUSH TABLES"); + stmt.execute("INSERT INTO my_table_" + columnName + "(my_col) VALUES (" + strValue + ")"); + stmt.execute("SELECT * FROM my_table_" + columnName); - try (Statement statement = sharedConnection.createStatement()) { - createTable("my_table", "my_col " + columnType); - statement.execute("INSERT INTO my_table(my_col) VALUES (" + strValue + ")"); - statement.execute("SELECT * FROM my_table"); - - try (ResultSet resultSet = statement.getResultSet()) { + try (ResultSet resultSet = stmt.getResultSet()) { ResultSetMetaData metaData = resultSet.getMetaData(); assertEquals( "class name for " + columnType, @@ -248,6 +256,7 @@ private void assertType( assertEquals(expectedObjectValue, objectValue); } } + stmt.execute("DROP TABLE my_table_" + columnName); } } diff --git a/src/test/java/org/mariadb/jdbc/DatatypeTest.java b/src/test/java/org/mariadb/jdbc/DatatypeTest.java index 58efe32cf..7fc105606 100644 --- a/src/test/java/org/mariadb/jdbc/DatatypeTest.java +++ b/src/test/java/org/mariadb/jdbc/DatatypeTest.java @@ -60,6 +60,7 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.sql.*; +import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -68,39 +69,114 @@ public class DatatypeTest extends BaseTest { private ResultSet resultSet; - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("Driverstreamtest", "id int not null primary key, strm text"); - createTable("Driverstreamtest2", "id int primary key not null, strm text"); - createTable( - "objecttest", - "int_test int primary key not null, string_test varchar(30), " - + "timestamp_test timestamp, serial_test blob"); - createTable( - "bintest", - "id int not null primary key auto_increment, bin1 varbinary(300), bin2 varbinary(300)"); - createTable( - "bigdectest", "id int not null primary key auto_increment, bd decimal", "engine=innodb"); - createTable("bytetest", "id int not null primary key auto_increment, a int", "engine=innodb"); - createTable("shorttest", "id int not null primary key auto_increment,a int", "engine=innodb"); - createTable( - "doubletest", "id int not null primary key auto_increment,a double", "engine=innodb"); - createTable("bittest", "id int not null primary key auto_increment, b int"); - createTable("emptytest", "id int"); - createTable( - "test_setobjectconv", - "id int not null primary key auto_increment, v1 varchar(40), v2 varchar(40)"); - createTable("blabla", "valsue varchar(20)"); - createTable("TestBigIntType", "t1 bigint(20), t2 bigint(20), t3 bigint(20), t4 bigint(20)"); - createTable( - "time_period", - "ID int unsigned NOT NULL, START time NOT NULL, END time NOT NULL, PRIMARY KEY (ID)"); - createTable("bitBoolTest", "d1 BOOLEAN, d2 BIT"); + afterClass(); + try (PreparedStatement prep = sharedConnection.prepareStatement("SELECT ?")) { + prep.setInt(1, 1000); + prep.execute(); // will send a query "SELECT 1000" + } + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE Driverstreamtest(id int not null primary key, strm text)"); + stmt.execute("CREATE TABLE Driverstreamtest2(id int primary key not null, strm text)"); + stmt.execute( + "CREATE TABLE objecttest(int_test int primary key not null, string_test varchar(30), timestamp_test timestamp, serial_test blob)"); + stmt.execute( + "CREATE TABLE bintest(id int not null primary key auto_increment, bin1 varbinary(300), bin2 varbinary(300))"); + stmt.execute( + "CREATE TABLE bigdectest(id int not null primary key auto_increment, bd decimal)"); + stmt.execute("CREATE TABLE bytetest(id int not null primary key auto_increment, a int)"); + stmt.execute("CREATE TABLE shorttest(id int not null primary key auto_increment,a int)"); + stmt.execute("CREATE TABLE doubletest(id int not null primary key auto_increment,a double)"); + stmt.execute("CREATE TABLE bittest(id int not null primary key auto_increment, b int)"); + stmt.execute("CREATE TABLE emptytest(id int)"); + stmt.execute( + "CREATE TABLE test_setobjectconv(id int not null primary key auto_increment, v1 varchar(40), v2 varchar(40))"); + stmt.execute("CREATE TABLE blabla(valsue varchar(20))"); + stmt.execute( + "CREATE TABLE TestBigIntType(t1 bigint(20), t2 bigint(20), t3 bigint(20), t4 bigint(20))"); + stmt.execute( + "CREATE TABLE time_period(ID int unsigned NOT NULL, START time NOT NULL, END time NOT NULL, PRIMARY KEY (ID))"); + stmt.execute("CREATE TABLE bitBoolTest(d1 BOOLEAN, d2 BIT)"); + stmt.execute("CREATE TABLE bintest2(bin1 longblob)"); + stmt.execute("CREATE TABLE bintest3(bin1 longblob)"); + stmt.execute("CREATE TABLE longMinValueSpecificity(ii BIGINT)"); + stmt.execute( + "CREATE TABLE datatypetest(" + + "bit1 BIT(1) default 0," + + "bit2 BIT(2) default 1," + + "tinyint1 TINYINT(1) default 0," + + "tinyint2 TINYINT(2) default 1," + + "bool0 BOOL default 0," + + "smallint0 SMALLINT default 1," + + "smallint_unsigned SMALLINT UNSIGNED default 0," + + "mediumint0 MEDIUMINT default 1," + + "mediumint_unsigned MEDIUMINT UNSIGNED default 0," + + "int0 INT default 1," + + "int_unsigned INT UNSIGNED default 0," + + "bigint0 BIGINT default 1," + + "bigint_unsigned BIGINT UNSIGNED default 0," + + "float0 FLOAT default 0," + + "double0 DOUBLE default 1," + + "decimal0 DECIMAL default 0," + + "date0 DATE default '2001-01-01'," + + "datetime0 DATETIME default '2001-01-01 00:00:00'," + + "timestamp0 TIMESTAMP default '2001-01-01 00:00:00'," + + "time0 TIME default '22:11:00'," + + ((minVersion(5, 6) && strictBeforeVersion(10, 0)) + ? "year2 YEAR(4) default 99," + : "year2 YEAR(2) default 99,") + + "year4 YEAR(4) default 2011," + + "char0 CHAR(1) default '0'," + + "char_binary CHAR (1) binary default '0'," + + "varchar0 VARCHAR(1) default '1'," + + "varchar_binary VARCHAR(10) BINARY default 0x1," + + "binary0 BINARY(10) default 0x1," + + "varbinary0 VARBINARY(10) default 0x1," + + "tinyblob0 TINYBLOB," + + "tinytext0 TINYTEXT," + + "blob0 BLOB," + + "bigvarchar VARCHAR(12383)," + + "text0 TEXT," + + "mediumblob0 MEDIUMBLOB," + + "mediumtext0 MEDIUMTEXT," + + "longblob0 LONGBLOB," + + "longtext0 LONGTEXT," + + "enum0 ENUM('a','b') default 'a'," + + "set0 SET('a','b') default 'a')"); + stmt.execute("CREATE TABLE LatinTable(t1 varchar(30)) DEFAULT CHARSET=latin1"); + stmt.execute("CREATE TABLE testShortBit(bitVal BIT(1), bitVal2 BIT(40))"); + stmt.execute("CREATE TABLE testTextNullValue(id int, val text)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS Driverstreamtest"); + stmt.execute("DROP TABLE IF EXISTS Driverstreamtest2"); + stmt.execute("DROP TABLE IF EXISTS objecttest"); + stmt.execute("DROP TABLE IF EXISTS bintest"); + stmt.execute("DROP TABLE IF EXISTS bigdectest"); + stmt.execute("DROP TABLE IF EXISTS bytetest"); + stmt.execute("DROP TABLE IF EXISTS shorttest"); + stmt.execute("DROP TABLE IF EXISTS doubletest"); + stmt.execute("DROP TABLE IF EXISTS bittest"); + stmt.execute("DROP TABLE IF EXISTS emptytest"); + stmt.execute("DROP TABLE IF EXISTS test_setobjectconv"); + stmt.execute("DROP TABLE IF EXISTS blabla"); + stmt.execute("DROP TABLE IF EXISTS TestBigIntType"); + stmt.execute("DROP TABLE IF EXISTS time_period"); + stmt.execute("DROP TABLE IF EXISTS bitBoolTest"); + stmt.execute("DROP TABLE IF EXISTS bintest2"); + stmt.execute("DROP TABLE IF EXISTS bintest3"); + stmt.execute("DROP TABLE IF EXISTS datatypetest"); + stmt.execute("DROP TABLE IF EXISTS longMinValueSpecificity"); + stmt.execute("DROP TABLE IF EXISTS LatinTable"); + stmt.execute("DROP TABLE IF EXISTS testShortBit"); + stmt.execute("DROP TABLE IF EXISTS testTextNullValue"); + } } /** @@ -165,52 +241,6 @@ private void checkClass(String column, Class clazz, String mysqlType, int jav resultSet.getMetaData().getColumnType(index)); } - private void createDataTypeTables() throws SQLException { - createTable( - "datatypetest", - "bit1 BIT(1) default 0," - + "bit2 BIT(2) default 1," - + "tinyint1 TINYINT(1) default 0," - + "tinyint2 TINYINT(2) default 1," - + "bool0 BOOL default 0," - + "smallint0 SMALLINT default 1," - + "smallint_unsigned SMALLINT UNSIGNED default 0," - + "mediumint0 MEDIUMINT default 1," - + "mediumint_unsigned MEDIUMINT UNSIGNED default 0," - + "int0 INT default 1," - + "int_unsigned INT UNSIGNED default 0," - + "bigint0 BIGINT default 1," - + "bigint_unsigned BIGINT UNSIGNED default 0," - + "float0 FLOAT default 0," - + "double0 DOUBLE default 1," - + "decimal0 DECIMAL default 0," - + "date0 DATE default '2001-01-01'," - + "datetime0 DATETIME default '2001-01-01 00:00:00'," - + "timestamp0 TIMESTAMP default '2001-01-01 00:00:00'," - + "time0 TIME default '22:11:00'," - + ((minVersion(5, 6) && strictBeforeVersion(10, 0)) - ? "year2 YEAR(4) default 99," - : "year2 YEAR(2) default 99,") - + "year4 YEAR(4) default 2011," - + "char0 CHAR(1) default '0'," - + "char_binary CHAR (1) binary default '0'," - + "varchar0 VARCHAR(1) default '1'," - + "varchar_binary VARCHAR(10) BINARY default 0x1," - + "binary0 BINARY(10) default 0x1," - + "varbinary0 VARBINARY(10) default 0x1," - + "tinyblob0 TINYBLOB," - + "tinytext0 TINYTEXT," - + "blob0 BLOB," - + "bigvarchar VARCHAR(12383)," - + "text0 TEXT," - + "mediumblob0 MEDIUMBLOB," - + "mediumtext0 MEDIUMTEXT," - + "longblob0 LONGBLOB," - + "longtext0 LONGTEXT," - + "enum0 ENUM('a','b') default 'a'," - + "set0 SET('a','b') default 'a' "); - } - /** * Testing different date parameters. * @@ -222,7 +252,7 @@ private void createDataTypeTables() throws SQLException { public void datatypes(Connection connection, boolean tinyInt1isBit, boolean yearIsDateType) throws Exception { - createDataTypeTables(); + connection.createStatement().execute("TRUNCATE TABLE datatypetest"); connection .createStatement() @@ -410,21 +440,24 @@ public void testLongColName() throws SQLException { for (int i = 0; i < dbmd.getMaxColumnNameLength(); i++) { str.append("x"); } - createTable("longcol", str + " int not null primary key"); - sharedConnection.createStatement().execute("insert into longcol values (1)"); - - try (ResultSet rs = getResultSet("select * from longcol", false)) { - assertEquals(true, rs.next()); - assertEquals(1, rs.getInt(1)); - assertEquals(1, rs.getInt(str.toString())); - assertEquals("1", rs.getString(1)); - } + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE longcol(" + str + " int not null primary key)"); + stmt.execute("FLUSH TABLES"); + stmt.execute("insert into longcol values (1)"); + try (ResultSet rs = getResultSet("select * from longcol", false)) { + assertEquals(true, rs.next()); + assertEquals(1, rs.getInt(1)); + assertEquals(1, rs.getInt(str.toString())); + assertEquals("1", rs.getString(1)); + } - try (ResultSet rs = getResultSet("select * from longcol", true)) { - assertEquals(true, rs.next()); - assertEquals(1, rs.getInt(1)); - assertEquals(1, rs.getInt(str.toString())); - assertEquals("1", rs.getString(1)); + try (ResultSet rs = getResultSet("select * from longcol", true)) { + assertEquals(true, rs.next()); + assertEquals(1, rs.getInt(1)); + assertEquals(1, rs.getInt(str.toString())); + assertEquals("1", rs.getString(1)); + } + stmt.execute("DROP TABLE longcol"); } } @@ -557,7 +590,7 @@ public void setObjectBitInt() throws SQLException { PreparedStatement preparedStatement = sharedConnection.prepareStatement( - "INSERT INTO TestBigIntType " + "(t1, t2, t3, t4) VALUES (?, ?, ?, ?)"); + "INSERT INTO TestBigIntType (t1, t2, t3, t4) VALUES (?, ?, ?, ?)"); final long valueLong = System.currentTimeMillis(); final String maxValue = String.valueOf(Long.MAX_VALUE); @@ -640,7 +673,6 @@ private void binTestResult(ResultSet rs, byte[] allBytes) throws SQLException, I @Test public void binTest2() throws SQLException { - createTable("bintest2", "bin1 longblob", "engine=innodb"); byte[] buf = new byte[1000000]; for (int i = 0; i < 1000000; i++) { @@ -675,7 +707,6 @@ public void binTest3() throws SQLException { InputStream is = new ByteArrayInputStream(buf); try (Connection connection = setConnection()) { - createTable("bintest3", "bin1 longblob", "engine=innodb"); Statement stmt = connection.createStatement(); try (PreparedStatement ps = @@ -971,7 +1002,6 @@ public void testNullTimePreparedStatement() throws Exception { @Test public void longMinValueSpecificity() throws SQLException { - createTable("longMinValueSpecificity", "ii BIGINT"); try (Statement statement = sharedConnection.createStatement()) { try (PreparedStatement preparedStatement = @@ -1001,8 +1031,6 @@ public void longMinValueSpecificity() throws SQLException { @Test public void testBinarySetter() throws Throwable { - createTable("LatinTable", "t1 varchar(30)", "DEFAULT CHARSET=latin1"); - try (Connection connection = DriverManager.getConnection( connU @@ -1063,7 +1091,6 @@ private void checkCharactersInsert(Connection connection) throws Throwable { */ @Test public void testBitValues() throws SQLException { - createTable("testShortBit", "bitVal BIT(1), bitVal2 BIT(40)"); Statement stmt = sharedConnection.createStatement(); stmt.execute( "INSERT INTO testShortBit VALUES (0,0), (1,1), (1, b'01010101'), (1, 21845), (1, b'1101010101010101')" @@ -1085,7 +1112,6 @@ public void testBitValues() throws SQLException { */ @Test public void testNullGetObject() throws SQLException { - createTable("testTextNullValue", "id int, val text"); Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO testTextNullValue VALUES (1, 'abc'), (2, null)"); ResultSet rs = stmt.executeQuery("SELECT * FROM testTextNullValue"); diff --git a/src/test/java/org/mariadb/jdbc/DateTest.java b/src/test/java/org/mariadb/jdbc/DateTest.java index e76fa3b06..6931a2aba 100644 --- a/src/test/java/org/mariadb/jdbc/DateTest.java +++ b/src/test/java/org/mariadb/jdbc/DateTest.java @@ -58,6 +58,7 @@ import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -67,27 +68,65 @@ public class DateTest extends BaseTest { private static final String TIMESTAMP_1 = "2015-05-13 08:15:14"; private static final String TIMESTAMP_YEAR_ZERO = "0000-11-15 10:15:22"; - /** - * Initialization. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("dtest", "d date"); - createTable( - "date_test2", "id int not null primary key auto_increment, d_from datetime ,d_to datetime"); - createTable("timetest", "t time"); - createTable("timetest2", "t time"); - createTable("timestampzerotest", "ts timestamp, dt datetime, dd date"); - createTable("dtest", "d datetime"); - createTable("dtest2", "d date"); - createTable("dtest3", "d date"); - createTable("dtest4", "d time"); - createTable("date_test3", " x date"); - createTable("date_test4", "x date"); - if (doPrecisionTest) { - createTable("timestampAsDate", "ts timestamp(6), dt datetime(6), dd date"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE dtest(d date)"); + stmt.execute( + "CREATE TABLE date_test2(id int not null primary key auto_increment, d_from datetime ,d_to datetime)"); + stmt.execute("CREATE TABLE timetest(t time)"); + stmt.execute("CREATE TABLE timetest2(t time)"); + stmt.execute("CREATE TABLE timestampzerotest(ts timestamp, dt datetime, dd date)"); + stmt.execute("CREATE TABLE dtest6(d datetime)"); + stmt.execute("CREATE TABLE dtest2(d date)"); + stmt.execute("CREATE TABLE dtest3(d date)"); + stmt.execute("CREATE TABLE dtest4(d time)"); + stmt.execute("CREATE TABLE date_test3(x date)"); + stmt.execute("CREATE TABLE date_test4(x date)"); + stmt.execute("CREATE TABLE date_test5(x date)"); + stmt.execute("CREATE TABLE nulltimestamp(ts timestamp(6) NULL)"); + stmt.execute("CREATE TABLE zeroTimestamp(ts timestamp NULL)"); + stmt.execute( + "CREATE TABLE date_test(id int not null primary key auto_increment, d_test date,dt_test datetime, " + + "t_test time)"); + boolean isMariadbServer = isMariadbServer(); + if (isMariadbServer) { + stmt.execute("CREATE TABLE yeartest(y1 year, y2 year(2))"); + stmt.execute( + "CREATE TABLE timestampMillisecondsTest(id decimal(10), create_time datetime(6))"); + } else { + stmt.execute( + "CREATE TABLE timestampMillisecondsTest(id decimal(10), create_time datetime)"); + } + if (doPrecisionTest) { + stmt.execute("CREATE TABLE timestampAsDate(ts timestamp(6), dt datetime(6), dd date)"); + } + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS dtest"); + stmt.execute("DROP TABLE IF EXISTS date_test"); + stmt.execute("DROP TABLE IF EXISTS date_test2"); + stmt.execute("DROP TABLE IF EXISTS timetest"); + stmt.execute("DROP TABLE IF EXISTS timetest2"); + stmt.execute("DROP TABLE IF EXISTS timestampzerotest"); + stmt.execute("DROP TABLE IF EXISTS dtest6"); + stmt.execute("DROP TABLE IF EXISTS dtest2"); + stmt.execute("DROP TABLE IF EXISTS dtest3"); + stmt.execute("DROP TABLE IF EXISTS dtest4"); + stmt.execute("DROP TABLE IF EXISTS date_test3"); + stmt.execute("DROP TABLE IF EXISTS date_test4"); + stmt.execute("DROP TABLE IF EXISTS timestampAsDate"); + stmt.execute("DROP TABLE IF EXISTS yeartest"); + stmt.execute("DROP TABLE IF EXISTS timestampMillisecondsTest"); + stmt.execute("DROP TABLE IF EXISTS date_test5"); + stmt.execute("DROP TABLE IF EXISTS nulltimestamp"); + stmt.execute("DROP TABLE IF EXISTS zeroTimestamp"); } } @@ -109,6 +148,7 @@ public void dateTestWithoutLegacy() throws SQLException { */ public void dateTest(boolean useLegacy) throws SQLException { Assume.assumeFalse(sharedIsRewrite()); + sharedConnection.createStatement().execute("TRUNCATE date_test"); try (Connection connection = setConnection( "&useLegacyDatetimeCode=" @@ -116,17 +156,14 @@ public void dateTest(boolean useLegacy) throws SQLException { + "&serverTimezone=+5:00&maximizeMysqlCompatibility=false&useServerPrepStmts=true")) { setSessionTimeZone(connection, "+5:00"); - createTable( - "date_test", - "id int not null primary key auto_increment, d_test date,dt_test datetime, " - + "t_test time"); + Statement stmt = connection.createStatement(); Date date = Date.valueOf("2009-01-17"); Timestamp timestamp = Timestamp.valueOf("2009-01-17 15:41:01"); Time time = Time.valueOf("23:59:59"); PreparedStatement ps = connection.prepareStatement( - "insert into date_test (d_test, dt_test, t_test) " + "values (?,?,?)"); + "insert into date_test (d_test, dt_test, t_test) values (?,?,?)"); ps.setDate(1, date); ps.setTimestamp(2, timestamp); ps.setTime(3, time); @@ -152,7 +189,7 @@ public void dateTest(boolean useLegacy) throws SQLException { public void dateRangeTest() throws SQLException { PreparedStatement ps = sharedConnection.prepareStatement( - "insert into date_test2 (id, d_from, d_to) values " + "(1, ?,?)"); + "insert into date_test2 (id, d_from, d_to) values (1, ?,?)"); Timestamp timestamp1 = Timestamp.valueOf("2009-01-17 15:41:01"); Timestamp timestamp2 = Timestamp.valueOf("2015-01-17 15:41:01"); ps.setTimestamp(1, timestamp1); @@ -160,7 +197,7 @@ public void dateRangeTest() throws SQLException { ps.executeUpdate(); PreparedStatement ps1 = sharedConnection.prepareStatement( - "select d_from, d_to from date_test2 " + "where d_from <= ? and d_to >= ?"); + "select d_from, d_to from date_test2 where d_from <= ? and d_to >= ?"); Timestamp timestamp3 = Timestamp.valueOf("2014-01-17 15:41:01"); ps1.setTimestamp(1, timestamp3); ps1.setTimestamp(2, timestamp3); @@ -199,7 +236,6 @@ public void timeTest3() throws SQLException { @Test public void yearTest() throws SQLException { Assume.assumeTrue(isMariadbServer()); - createTable("yeartest", "y1 year, y2 year(2)"); sharedConnection .createStatement() .execute("insert into yeartest values (null, null), (1901, 70), (0, 0), (2155, 69)"); @@ -430,10 +466,10 @@ private void checkResult( @Test public void javaUtilDateInPreparedStatementAsTimeStamp() throws Exception { java.util.Date currentDate = Calendar.getInstance(TimeZone.getDefault()).getTime(); - PreparedStatement ps = sharedConnection.prepareStatement("insert into dtest values(?)"); + PreparedStatement ps = sharedConnection.prepareStatement("insert into dtest6 values(?)"); ps.setObject(1, currentDate, Types.TIMESTAMP); ps.executeUpdate(); - ResultSet rs = sharedConnection.createStatement().executeQuery("select * from dtest"); + ResultSet rs = sharedConnection.createStatement().executeQuery("select * from dtest6"); assertTrue(rs.next()); /* Check that time is correct, up to seconds precision */ assertTrue(Math.abs((currentDate.getTime() - rs.getTimestamp(1).getTime())) <= 1000); @@ -529,20 +565,21 @@ public void timestampMillisecondsTest() throws SQLException { boolean isMariadbServer = isMariadbServer(); if (isMariadbServer) { - createTable("tt", "id decimal(10), create_time datetime(6)"); - statement.execute("INSERT INTO tt (id, create_time) VALUES (1,'2013-07-18 13:44:22.123456')"); + statement.execute( + "INSERT INTO timestampMillisecondsTest (id, create_time) VALUES (1,'2013-07-18 13:44:22.123456')"); } else { - createTable("tt", "id decimal(10), create_time datetime"); - statement.execute("INSERT INTO tt (id, create_time) VALUES (1,'2013-07-18 13:44:22')"); + statement.execute( + "INSERT INTO timestampMillisecondsTest (id, create_time) VALUES (1,'2013-07-18 13:44:22')"); } PreparedStatement ps = - sharedConnection.prepareStatement("insert into tt (id, create_time) values (?,?)"); + sharedConnection.prepareStatement( + "insert into timestampMillisecondsTest (id, create_time) values (?,?)"); ps.setInt(1, 2); Timestamp writeTs = new Timestamp(1273017612999L); Timestamp writeTsWithoutMilliSec = new Timestamp(1273017612999L); ps.setTimestamp(2, writeTs); ps.execute(); - ResultSet rs = statement.executeQuery("SELECT * FROM tt"); + ResultSet rs = statement.executeQuery("SELECT * FROM timestampMillisecondsTest"); assertTrue(rs.next()); if (isMariadbServer) { assertTrue("2013-07-18 13:44:22.123456".equals(rs.getString(2))); @@ -607,7 +644,6 @@ public void dateTestWhenServerDifferenceClient() throws Throwable { public void nullDateString() throws Throwable { // null date isn't accepted anymore for mysql. Assume.assumeFalse(!isMariadbServer() && minVersion(5, 7, 0)); - createTable("date_test5", "x date"); Statement stmt = sharedConnection.createStatement(); try { stmt.execute("INSERT INTO date_test5 (x) VALUES ('0000-00-00')"); @@ -636,8 +672,6 @@ public void nullDateString() throws Throwable { @Test public void nullDateFromTimestamp() throws Throwable { Assume.assumeTrue(isMariadbServer()); - - createTable("nulltimestamp", "ts timestamp(6) NULL "); Statement stmt = sharedConnection.createStatement(); try { stmt.execute("INSERT INTO nulltimestamp (ts) VALUES ('0000-00-00'), (null)"); @@ -675,7 +709,6 @@ public void nullDateFromTimestamp() throws Throwable { @Test public void getZeroDateString() throws SQLException { Assume.assumeTrue(isMariadbServer()); - createTable("zeroTimestamp", "ts timestamp NULL "); try (Statement statement = sharedConnection.createStatement()) { statement.execute("INSERT INTO zeroTimestamp values ('0000-00-00 00:00:00')"); try (PreparedStatement preparedStatement = diff --git a/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java b/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java index 30b0314c9..8cd92062c 100644 --- a/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java +++ b/src/test/java/org/mariadb/jdbc/DistributedTransactionTest.java @@ -57,17 +57,36 @@ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.UUID; import javax.sql.XAConnection; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; public class DistributedTransactionTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE xatable(i int)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS xatable"); + } + } + private final MariaDbDataSource dataSource; /** Initialisation. */ @@ -80,12 +99,6 @@ public DistributedTransactionTest() throws SQLException { dataSource.setPassword(password); } - @BeforeClass() - public static void initClass() throws SQLException { - Assume.assumeFalse(options.useSsl != null && options.useSsl); - createTable("xatable", "i int", "ENGINE=InnoDB"); - } - private Xid newXid() { return new MariaDbXid( 1, UUID.randomUUID().toString().getBytes(), UUID.randomUUID().toString().getBytes()); @@ -236,6 +249,7 @@ public void resumeAndJoinTest() throws Exception { ds.setUser(username); ds.setPassword(password); ds.setPort(port); + XAConnection xaConn1 = null; Xid xid = newXid(); try { diff --git a/src/test/java/org/mariadb/jdbc/DriverTest.java b/src/test/java/org/mariadb/jdbc/DriverTest.java index a2c3f8cdc..96b4d04fc 100644 --- a/src/test/java/org/mariadb/jdbc/DriverTest.java +++ b/src/test/java/org/mariadb/jdbc/DriverTest.java @@ -62,75 +62,116 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.mariadb.jdbc.internal.util.DeRegister; import org.mariadb.jdbc.internal.util.constant.HaMode; import org.mariadb.jdbc.util.DefaultOptions; public class DriverTest extends BaseTest { - private static int namedPipeBusyTestError = 0; - - /** - * Tables initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("tt1", "id int , name varchar(20)"); - createTable("tt2", "id int , name varchar(20)"); - createTable("Drivert2", "id int not null primary key auto_increment, test varchar(10)"); - createTable("utente", "id int not null primary key auto_increment, test varchar(10)"); - - createTable("Drivert3", "id int not null primary key auto_increment, test varchar(10)"); - createTable( - "Drivert30", - "id int not null primary key auto_increment, test varchar(20)", - "engine=innodb"); - createTable( - "Drivert4", - "id int not null primary key auto_increment, test varchar(20)", - "engine=innodb"); - createTable( - "Drivert5", - "id int not null primary key auto_increment, test varchar(20)", - "engine=innodb"); - createTable( - "Drivert6", - "id int not null primary key auto_increment, test varchar(20)", - "engine=innodb"); - createTable("test_float", "id int not null primary key auto_increment, a float"); - createTable( - "test_big_autoinc2", "id int not null primary key auto_increment, test varchar(10)"); - createTable("test_big_update", "id int primary key not null, updateme int"); - createTable("sharedConnection", "id int"); - createTable("extest", "id int not null primary key"); - createTable( - "commentPreparedStatements", "id int not null primary key auto_increment, a varchar(10)"); - createTable( - "quotesPreparedStatements", - "id int not null primary key auto_increment, a varchar(10) , " + "b varchar(10)"); - createTable("ressetpos", "i int not null primary key", "engine=innodb"); - createTable("streamingressetpos", "i int not null primary key", "engine=innodb"); - createTable("streamingtest", "val varchar(20)"); - createTable("testBlob2", "a blob"); - createTable("testString2", "a varchar(10)"); - createTable("testBlob2", "a blob"); - createTable("unsignedtest", "a int unsigned"); - createTable("conj25", "a VARCHAR(1024)"); - createTable("DriverTestt1", "id int not null primary key auto_increment, test varchar(20)"); - createTable("DriverTestt2", "id int not null primary key auto_increment, test varchar(20)"); - createTable("DriverTestt3", "id int not null primary key auto_increment, test varchar(20)"); - createTable("DriverTestt4", "id int not null primary key auto_increment, test varchar(20)"); - createTable("DriverTestt5", "id int not null primary key auto_increment, test varchar(20)"); - createProcedure("foo", "() BEGIN SELECT 1; END"); - createTable("conj275", "a VARCHAR(10)"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE tt1(id int , name varchar(20))"); + stmt.execute("CREATE TABLE tt2(id int , name varchar(20))"); + stmt.execute( + "CREATE TABLE Drivert2(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE utente(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE Drivert3(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute( + "CREATE TABLE Drivert30(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE Drivert4(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE Drivert5(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE Drivert6(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute("CREATE TABLE test_float(id int not null primary key auto_increment, a float)"); + stmt.execute( + "CREATE TABLE test_big_autoinc2(id int not null primary key auto_increment, test varchar(10))"); + stmt.execute("CREATE TABLE test_big_update(id int primary key not null, updateme int)"); + stmt.execute("CREATE TABLE sharedConnection(id int)"); + stmt.execute("CREATE TABLE extest(id int not null primary key)"); + stmt.execute( + "CREATE TABLE commentPreparedStatements(id int not null primary key auto_increment, a varchar(10))"); + stmt.execute( + "CREATE TABLE quotesPreparedStatements(id int not null primary key auto_increment, a varchar(10) , b varchar(10))"); + stmt.execute("CREATE TABLE ressetpos(i int not null primary key)"); + stmt.execute("CREATE TABLE streamingressetpos(i int not null primary key)"); + stmt.execute("CREATE TABLE streamingtest(val varchar(20))"); + stmt.execute("CREATE TABLE testString2(a varchar(10))"); + stmt.execute("CREATE TABLE testBlob2(a blob)"); + stmt.execute("CREATE TABLE unsignedtest(a int unsigned)"); + stmt.execute("CREATE TABLE conj25(a VARCHAR(1024))"); + stmt.execute( + "CREATE TABLE DriverTestt1(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE DriverTestt2(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE DriverTestt3(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE DriverTestt4(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE DriverTestt5(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute("CREATE TABLE conj275(a VARCHAR(10))"); + stmt.execute("CREATE TABLE testLongEscapes(t1 longtext)"); + stmt.execute( + "CREATE TABLE testRollbackOnClose(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute( + "CREATE TABLE testAutoCommit(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute("CREATE TABLE escapeTest(t varchar(10))"); + stmt.execute("CREATE PROCEDURE foo() BEGIN SELECT 1; END"); + stmt.execute("CREATE PROCEDURE multiUpdateCount() BEGIN SELECT 1; SELECT 2; END"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS tt1"); + stmt.execute("DROP TABLE IF EXISTS tt2"); + stmt.execute("DROP TABLE IF EXISTS Drivert2"); + stmt.execute("DROP TABLE IF EXISTS utente"); + stmt.execute("DROP TABLE IF EXISTS Drivert3"); + stmt.execute("DROP TABLE IF EXISTS Drivert30"); + stmt.execute("DROP TABLE IF EXISTS Drivert4"); + stmt.execute("DROP TABLE IF EXISTS Drivert5"); + stmt.execute("DROP TABLE IF EXISTS Drivert6"); + stmt.execute("DROP TABLE IF EXISTS test_float"); + stmt.execute("DROP TABLE IF EXISTS test_big_autoinc2"); + stmt.execute("DROP TABLE IF EXISTS test_big_update"); + stmt.execute("DROP TABLE IF EXISTS sharedConnection"); + stmt.execute("DROP TABLE IF EXISTS extest"); + stmt.execute("DROP TABLE IF EXISTS commentPreparedStatements"); + stmt.execute("DROP TABLE IF EXISTS quotesPreparedStatements"); + stmt.execute("DROP TABLE IF EXISTS ressetpos"); + stmt.execute("DROP TABLE IF EXISTS streamingressetpos"); + stmt.execute("DROP TABLE IF EXISTS streamingtest"); + stmt.execute("DROP TABLE IF EXISTS testString2"); + stmt.execute("DROP TABLE IF EXISTS testBlob2"); + stmt.execute("DROP TABLE IF EXISTS unsignedtest"); + stmt.execute("DROP TABLE IF EXISTS conj25"); + stmt.execute("DROP TABLE IF EXISTS DriverTestt1"); + stmt.execute("DROP TABLE IF EXISTS DriverTestt2"); + stmt.execute("DROP TABLE IF EXISTS DriverTestt3"); + stmt.execute("DROP TABLE IF EXISTS DriverTestt4"); + stmt.execute("DROP TABLE IF EXISTS DriverTestt5"); + stmt.execute("DROP TABLE IF EXISTS conj275"); + stmt.execute("DROP TABLE IF EXISTS testLongEscapes"); + stmt.execute("DROP TABLE IF EXISTS testRollbackOnClose"); + stmt.execute("DROP TABLE IF EXISTS testAutoCommit"); + stmt.execute("DROP TABLE IF EXISTS escapeTest"); + stmt.execute("DROP PROCEDURE IF EXISTS foo"); + stmt.execute("DROP PROCEDURE IF EXISTS multiUpdateCount"); + } } + private static int namedPipeBusyTestError = 0; + @Test public void doQuery() throws SQLException { Statement stmt = sharedConnection.createStatement(); @@ -234,7 +275,7 @@ public void parameterMetaDataTypeNotAvailable() throws SQLException { @Test public void parameterMetaDataNotPreparable() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeFalse(sharedUsePrepare()); Statement stmt = sharedConnection.createStatement(); Map initValues = loadVariables(stmt); @@ -278,7 +319,7 @@ private Map loadVariables(Statement stmt) throws SQLException { @Test public void parameterMetaDataPreparable() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeFalse(sharedUsePrepare()); Statement stmt = sharedConnection.createStatement(); Map initValues = loadVariables(stmt); @@ -672,7 +713,6 @@ public void testEscapes() throws SQLException { @Test public void escapeTest() throws SQLException { - createTable("escapeTest", "t varchar(10)"); String param = "a'\""; param += String.valueOf(10); param += String.valueOf(13); @@ -743,26 +783,31 @@ public void floatingNumbersTest() throws SQLException { @Test public void manyColumnsTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists test_many_columns"); - StringBuilder query = - new StringBuilder("create table test_many_columns (a0 int primary key not null"); - for (int i = 1; i < 1000; i++) { - query.append(",a").append(i).append(" int"); - } - query.append(")"); - stmt.execute(query.toString()); - query = new StringBuilder("insert into test_many_columns values (0"); - for (int i = 1; i < 1000; i++) { - query.append(",").append(i); - } - query.append(")"); - stmt.execute(query.toString()); - ResultSet rs = stmt.executeQuery("select * from test_many_columns"); + try { + stmt.execute("drop table if exists test_many_columns"); + StringBuilder query = + new StringBuilder("create table test_many_columns (a0 int primary key not null"); + for (int i = 1; i < 1000; i++) { + query.append(",a").append(i).append(" int"); + } + query.append(")"); + stmt.execute(query.toString()); + stmt.execute("FLUSH TABLES"); + query = new StringBuilder("insert into test_many_columns values (0"); + for (int i = 1; i < 1000; i++) { + query.append(",").append(i); + } + query.append(")"); + stmt.execute(query.toString()); + ResultSet rs = stmt.executeQuery("select * from test_many_columns"); - assertEquals(true, rs.next()); + assertEquals(true, rs.next()); - for (int i = 0; i < 1000; i++) { - assertEquals(rs.getInt("a" + i), i); + for (int i = 0; i < 1000; i++) { + assertEquals(rs.getInt("a" + i), i); + } + } finally { + stmt.execute("drop table if exists test_many_columns"); } } @@ -1018,7 +1063,6 @@ public void testUpdateCountMulti() throws SQLException { */ @Test public void testUpdateCountProcedure() throws SQLException { - createProcedure("multiUpdateCount", "() BEGIN SELECT 1; SELECT 2; END"); CallableStatement callableStatement = sharedConnection.prepareCall("{call multiUpdateCount()}"); callableStatement.execute(); assertTrue(-1 == callableStatement.getUpdateCount()); @@ -1028,7 +1072,7 @@ public void testUpdateCountProcedure() throws SQLException { @Test public void testConnectWithDb() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); requireMinimumVersion(5, 0); try { @@ -1082,7 +1126,7 @@ public void noBackslashEscapes() throws SQLException { assertTrue(rs.next()); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",NO_BACKSLASH_ESCAPES'"); - + st.execute("TRUNCATE testBlob2"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = @@ -1153,7 +1197,7 @@ public void ansiQuotes() throws SQLException { assertTrue(rs.next()); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",ANSI_QUOTES'"); - + st.execute("TRUNCATE testBlob2"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = @@ -1196,7 +1240,7 @@ public void mdev3916() throws Exception { @Test public void conj1() throws Exception { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); requireMinimumVersion(5, 0); @@ -1599,8 +1643,6 @@ public void checkStreamingWithoutResult() throws Exception { public void testLongEscapes() throws SQLException { // 40m, because escaping will double the send byte numbers Assume.assumeTrue(checkMaxAllowedPacketMore40m("testLongEscapes")); - createTable("testLongEscapes", "t1 longtext"); - try (PreparedStatement preparedStatement = sharedConnection.prepareStatement("INSERT into testLongEscapes values (?)")) { byte[] arr = new byte[20_000_000]; @@ -1625,8 +1667,6 @@ public void testLongEscapes() throws SQLException { @Test public void testRollbackOnClose() throws SQLException { - createTable( - "testRollbackOnClose", "id int not null primary key auto_increment, test varchar(20)"); try (Connection connection = setConnection()) { Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO testRollbackOnClose (test) VALUES ('heja')"); @@ -1644,8 +1684,6 @@ public void testRollbackOnClose() throws SQLException { @Test public void testAutoCommit() throws SQLException { - createTable("testAutoCommit", "id int not null primary key auto_increment, test varchar(20)"); - try (Connection connection = setConnection()) { assertTrue(connection.getAutoCommit()); Statement stmt = connection.createStatement(); @@ -1674,7 +1712,7 @@ public void testAutoCommit() throws SQLException { @Test public void databaseType() throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(System.getenv("TRAVIS") != null); boolean isMysql = System.getenv("AURORA") != null || System.getenv("DB").contains("mysql"); assertEquals( diff --git a/src/test/java/org/mariadb/jdbc/ErrorMessageTest.java b/src/test/java/org/mariadb/jdbc/ErrorMessageTest.java index 7042ce507..3a5aabcd3 100644 --- a/src/test/java/org/mariadb/jdbc/ErrorMessageTest.java +++ b/src/test/java/org/mariadb/jdbc/ErrorMessageTest.java @@ -59,6 +59,7 @@ import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -66,22 +67,27 @@ public class ErrorMessageTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "testErrorMessage", - "id int not null primary key auto_increment, test varchar(10), test2 int"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE testErrorMessage(id int not null primary key auto_increment, test varchar(10), test2 int)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS testErrorMessage"); + } } @Test public void testSmallRewriteErrorMessage() { try (Connection connection = - setBlankConnection("&rewriteBatchedStatements=true" + "&dumpQueriesOnException")) { + setBlankConnection("&rewriteBatchedStatements=true&dumpQueriesOnException")) { executeBatchWithException(connection); fail("Must Have thrown error"); } catch (SQLException sqle) { @@ -131,7 +137,7 @@ public void testSmallMultiBatchErrorMessage() throws SQLException { @Test public void testSmallPrepareErrorMessage() { try (Connection connection = - setBlankConnection("&useBatchMultiSend=false" + "&dumpQueriesOnException")) { + setBlankConnection("&useBatchMultiSend=false&dumpQueriesOnException")) { executeBatchWithException(connection); fail("Must Have thrown error"); } catch (SQLException sqle) { @@ -180,14 +186,14 @@ public void testSmallPrepareBulkErrorMessage() { assertTrue( sqle.getCause() .getMessage() - .contains("INSERT INTO testErrorMessage(test, test2) values " + "(?, ?)")); + .contains("INSERT INTO testErrorMessage(test, test2) values (?, ?)")); } } @Test public void testBigRewriteErrorMessage() { try (Connection connection = - setBlankConnection("&rewriteBatchedStatements=true" + "&dumpQueriesOnException")) { + setBlankConnection("&rewriteBatchedStatements=true&dumpQueriesOnException")) { executeBigBatchWithException(connection); fail("Must Have thrown error"); } catch (SQLException sqle) { @@ -238,7 +244,7 @@ public void testBigMultiErrorMessage() throws SQLException { @Test public void testBigPrepareErrorMessage() throws SQLException { try (Connection connection = - setBlankConnection("&useBatchMultiSend=false" + "&dumpQueriesOnException")) { + setBlankConnection("&useBatchMultiSend=false&dumpQueriesOnException")) { executeBigBatchWithException(connection); fail("Must Have thrown error"); } catch (SQLException sqle) { @@ -264,8 +270,7 @@ public void testBigPrepareErrorMessage() throws SQLException { @Test public void testBigBulkErrorMessage() throws SQLException { Assume.assumeFalse(sharedIsAurora()); - try (Connection connection = - setConnection("&useBatchMultiSend=true" + "&dumpQueriesOnException")) { + try (Connection connection = setConnection("&useBatchMultiSend=true&dumpQueriesOnException")) { executeBigBatchWithException(connection); fail("Must Have thrown error"); } catch (SQLException sqle) { @@ -348,7 +353,9 @@ private void executeBigBatchWithException(Connection connection) throws SQLExcep @Test public void testFailOverKillCmd() throws Throwable { Assume.assumeTrue( - System.getenv("MAXSCALE_TEST_DISABLE") == null && System.getenv("SKYSQL") == null); + System.getenv("MAXSCALE_TEST_DISABLE") == null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(isMariadbServer()); DataSource ds = new MariaDbDataSource( @@ -449,8 +456,7 @@ public void testSmallPrepareErrorMessageNoBulk() { public void testSmallBulkErrorMessageNoBulk() { Assume.assumeFalse(sharedIsAurora()); try (Connection connection = - setBlankConnection( - "&useBatchMultiSend=true&useBulkStmts=false" + "&dumpQueriesOnException")) { + setBlankConnection("&useBatchMultiSend=true&useBulkStmts=false&dumpQueriesOnException")) { executeBatchWithException(connection); fail("Must Have thrown error"); } catch (SQLException sqle) { @@ -474,9 +480,10 @@ public void testSmallPrepareBulkErrorMessageNoBulk() { fail("Must Have thrown error"); } catch (SQLException sqle) { assertTrue( + sqle.getCause().getMessage(), sqle.getCause() .getMessage() - .contains("INSERT INTO testErrorMessage(test, test2) values " + "(?, ?)")); + .contains("INSERT INTO testErrorMessage(test, test2) values (?, ?)")); } } @@ -545,8 +552,7 @@ public void testBigPrepareErrorMessageNoBulk() { public void testBigBulkErrorMessageNoBulk() { Assume.assumeFalse(sharedIsAurora()); try (Connection connection = - setBlankConnection( - "&useBatchMultiSend=true&useBulkStmts=false" + "&dumpQueriesOnException")) { + setBlankConnection("&useBatchMultiSend=true&useBulkStmts=false&dumpQueriesOnException")) { executeBigBatchWithException(connection); fail("Must Have thrown error"); } catch (SQLException sqle) { diff --git a/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java b/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java index 2422cbe57..78c11a2b7 100644 --- a/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java +++ b/src/test/java/org/mariadb/jdbc/ExecuteBatchTest.java @@ -64,6 +64,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -81,17 +82,22 @@ public class ExecuteBatchTest extends BaseTest { oneHundredLengthString = new String(chars); } - /** - * Create test tables. - * - * @throws SQLException if connection error occur - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "ExecuteBatchTest", - "id int not null primary key auto_increment, test varchar(100) , test2 int"); - createTable("ExecuteBatchUseBatchMultiSend", "test varchar(100)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE ExecuteBatchTest(id int not null primary key auto_increment, test varchar(100) , test2 int)"); + stmt.execute("CREATE TABLE ExecuteBatchUseBatchMultiSend(test varchar(100))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS ExecuteBatchTest"); + stmt.execute("DROP TABLE IF EXISTS ExecuteBatchUseBatchMultiSend"); + } } /** @@ -357,50 +363,54 @@ public void useBatchMultiSend() throws Exception { public void ensureBulkSchedulerMaxPoolSizeRejection() throws Throwable { Assume.assumeFalse(sharedIsAurora() || sharedOptions().profileSql); - Statement statement = sharedConnection.createStatement(); - ResultSet resultSet = statement.executeQuery("SELECT @@max_connections"); + Statement stmt = sharedConnection.createStatement(); + ResultSet resultSet = stmt.executeQuery("SELECT @@max_connections"); assertTrue(resultSet.next()); int maxConnection = resultSet.getInt(1); int limit = Math.min(1, Math.min(200, maxConnection - 10)); + try { + for (int i = 0; i < limit; i++) { + stmt.execute("CREATE TABLE multipleSimultaneousBatch_" + i + "(a INT NOT NULL)"); + } - for (int i = 0; i < limit; i++) { - createTable("multipleSimultaneousBatch_" + i, "a INT NOT NULL"); - } - - AtomicInteger counter = new AtomicInteger(); - ExecutorService exec = Executors.newFixedThreadPool(limit + 50); - for (int i = 0; i < limit; i++) { - exec.execute( - () -> { - try (Connection connection = setConnection()) { - connection.setAutoCommit(false); - Statement stmt = connection.createStatement(); - int connectionCounter = counter.getAndIncrement(); - for (int j = 0; j < 1024; j++) { - stmt.addBatch( - "INSERT INTO multipleSimultaneousBatch_" - + connectionCounter - + "(a) VALUES (" - + j - + ")"); + AtomicInteger counter = new AtomicInteger(); + ExecutorService exec = Executors.newFixedThreadPool(limit + 50); + for (int i = 0; i < limit; i++) { + exec.execute( + () -> { + try (Connection connection = setConnection()) { + connection.setAutoCommit(false); + Statement st = connection.createStatement(); + int connectionCounter = counter.getAndIncrement(); + for (int j = 0; j < 1024; j++) { + st.addBatch( + "INSERT INTO multipleSimultaneousBatch_" + + connectionCounter + + "(a) VALUES (" + + j + + ")"); + } + st.executeBatch(); + connection.commit(); + } catch (Throwable e) { + e.printStackTrace(); } - stmt.executeBatch(); - connection.commit(); - } catch (Throwable e) { - e.printStackTrace(); - } - }); - } + }); + } - exec.shutdown(); - exec.awaitTermination(150, TimeUnit.SECONDS); + exec.shutdown(); + exec.awaitTermination(150, TimeUnit.SECONDS); - // check results - Statement stmt = sharedConnection.createStatement(); - for (int i = 0; i < limit; i++) { - ResultSet rs = stmt.executeQuery("SELECT count(*) from multipleSimultaneousBatch_" + i); - assertTrue(rs.next()); - assertEquals(1024, rs.getInt(1)); + // check results + for (int i = 0; i < limit; i++) { + ResultSet rs = stmt.executeQuery("SELECT count(*) from multipleSimultaneousBatch_" + i); + assertTrue(rs.next()); + assertEquals(1024, rs.getInt(1)); + } + } finally { + for (int i = 0; i < limit; i++) { + stmt.execute("DROP TABLE multipleSimultaneousBatch_" + i); + } } } diff --git a/src/test/java/org/mariadb/jdbc/FetchSizeTest.java b/src/test/java/org/mariadb/jdbc/FetchSizeTest.java index fba83fbf5..c11666703 100644 --- a/src/test/java/org/mariadb/jdbc/FetchSizeTest.java +++ b/src/test/java/org/mariadb/jdbc/FetchSizeTest.java @@ -58,20 +58,34 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; public class FetchSizeTest extends BaseTest { - /** Tables initialisation. */ @BeforeClass() public static void initClass() throws SQLException { - createTable("fetchSizeTest1", "id int, test varchar(100)"); - createTable("fetchSizeTest2", "id int, test varchar(100)"); - createTable("fetchSizeTest3", "id int, test varchar(100)"); - createTable("fetchSizeTest4", "id int, test varchar(100)"); - createTable("fetchSizeTest5", "id int, test varchar(100)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE fetchSizeTest1(id int, test varchar(100))"); + stmt.execute("CREATE TABLE fetchSizeTest2(id int, test varchar(100))"); + stmt.execute("CREATE TABLE fetchSizeTest3(id int, test varchar(100))"); + stmt.execute("CREATE TABLE fetchSizeTest4(id int, test varchar(100))"); + stmt.execute("CREATE TABLE fetchSizeTest5(id int, test varchar(100))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS fetchSizeTest1"); + stmt.execute("DROP TABLE IF EXISTS fetchSizeTest2"); + stmt.execute("DROP TABLE IF EXISTS fetchSizeTest3"); + stmt.execute("DROP TABLE IF EXISTS fetchSizeTest4"); + stmt.execute("DROP TABLE IF EXISTS fetchSizeTest5"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/GeneratedKeysTest.java b/src/test/java/org/mariadb/jdbc/GeneratedKeysTest.java index 621f8729d..053450b21 100644 --- a/src/test/java/org/mariadb/jdbc/GeneratedKeysTest.java +++ b/src/test/java/org/mariadb/jdbc/GeneratedKeysTest.java @@ -55,23 +55,30 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; public class GeneratedKeysTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "gen_key_test", "id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY (id)"); - createTable( - "gen_key_test2", "id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY (id)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE gen_key_test(id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY (id))"); + stmt.execute( + "CREATE TABLE gen_key_test2(id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY (id))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS gen_key_test"); + stmt.execute("DROP TABLE IF EXISTS gen_key_test2"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/GeneratedTest.java b/src/test/java/org/mariadb/jdbc/GeneratedTest.java index 392072283..485aad673 100644 --- a/src/test/java/org/mariadb/jdbc/GeneratedTest.java +++ b/src/test/java/org/mariadb/jdbc/GeneratedTest.java @@ -57,21 +57,26 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class GeneratedTest extends BaseTest { - /** - * Tables initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "genkeys", - "priKey INT NOT NULL AUTO_INCREMENT, dataField VARCHAR(64), PRIMARY KEY (priKey)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE genkeys(priKey INT NOT NULL AUTO_INCREMENT, dataField VARCHAR(64), PRIMARY KEY (priKey))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE genkeys"); + } } /* diff --git a/src/test/java/org/mariadb/jdbc/GeometryTest.java b/src/test/java/org/mariadb/jdbc/GeometryTest.java index fbabf2605..470631d77 100644 --- a/src/test/java/org/mariadb/jdbc/GeometryTest.java +++ b/src/test/java/org/mariadb/jdbc/GeometryTest.java @@ -58,6 +58,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -65,14 +66,19 @@ public class GeometryTest extends BaseTest { private static final char[] hexCode = "0123456789ABCDEF".toCharArray(); - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("geom_test", "g geometry"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE geom_test(g geometry)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE geom_test"); + } } private void geometryTest(String geometryString, String geometryBinary) throws SQLException { diff --git a/src/test/java/org/mariadb/jdbc/GiganticLoadDataInfileTest.java b/src/test/java/org/mariadb/jdbc/GiganticLoadDataInfileTest.java index 2714c37fb..65471c2ad 100644 --- a/src/test/java/org/mariadb/jdbc/GiganticLoadDataInfileTest.java +++ b/src/test/java/org/mariadb/jdbc/GiganticLoadDataInfileTest.java @@ -61,23 +61,27 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class GiganticLoadDataInfileTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "gigantic_load_data_infile", - "id int not null primary key auto_increment, name char(20)", - "ENGINE=myisam"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE gigantic_load_data_infile(id int not null primary key auto_increment, name char(20)) ENGINE=myisam"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE gigantic_load_data_infile"); + } } @Ignore diff --git a/src/test/java/org/mariadb/jdbc/LocalInfileDisableTest.java b/src/test/java/org/mariadb/jdbc/LocalInfileDisableTest.java index 1c054dd9a..71b33ad98 100644 --- a/src/test/java/org/mariadb/jdbc/LocalInfileDisableTest.java +++ b/src/test/java/org/mariadb/jdbc/LocalInfileDisableTest.java @@ -58,19 +58,25 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class LocalInfileDisableTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("t", "id int, test varchar(100)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE LocalInfileDisableTest(id int, test varchar(100))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE LocalInfileDisableTest"); + } } @Test @@ -78,7 +84,8 @@ public void testLocalInfileWithoutInputStream() throws SQLException { try (Connection connection = setConnection("&allowLocalInfile=false")) { Exception ex = null; try (Statement stmt = connection.createStatement()) { - stmt.executeUpdate("LOAD DATA LOCAL INFILE 'dummy.tsv' INTO TABLE t (id, test)"); + stmt.executeUpdate( + "LOAD DATA LOCAL INFILE 'dummy.tsv' INTO TABLE LocalInfileDisableTest (id, test)"); } catch (Exception e) { ex = e; } diff --git a/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java b/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java index 3705ac122..2705a3549 100644 --- a/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java +++ b/src/test/java/org/mariadb/jdbc/LocalInfileInputStreamTest.java @@ -56,32 +56,39 @@ import java.io.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; public class LocalInfileInputStreamTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("LocalInfileInputStreamTest", "id int, test varchar(100)"); - createTable("ttlocal", "id int, test varchar(100)"); - createTable("ldinfile", "a varchar(10)"); - createTable( - "`infile`", - "`a` varchar(50) DEFAULT NULL, `b` varchar(50) DEFAULT NULL", - "ENGINE=InnoDB DEFAULT CHARSET=latin1"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE LocalInfileInputStreamTest(id int, test varchar(100))"); + stmt.execute("CREATE TABLE ttlocal(id int, test varchar(100))"); + stmt.execute("CREATE TABLE ldinfile(a varchar(10))"); + stmt.execute( + "CREATE TABLE `infile`(`a` varchar(50) DEFAULT NULL, `b` varchar(50) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS LocalInfileInputStreamTest"); + stmt.execute("DROP TABLE IF EXISTS ttlocal"); + stmt.execute("DROP TABLE IF EXISTS ldinfile"); + stmt.execute("DROP TABLE IF EXISTS `infile`"); + } } @Test public void testLocalInfileInputStream() throws SQLException { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); try (Connection connection = setConnection("&allowLocalInfile=true")) { try (Statement st = connection.createStatement()) { // Build a tab-separated record file @@ -109,7 +116,7 @@ public void testLocalInfileInputStream() throws SQLException { @Test public void testLocalInfileValidInterceptor() throws Exception { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); File temp = File.createTempFile("validateInfile", ".txt"); StringBuilder builder = new StringBuilder(); builder.append("1,hello\n"); @@ -125,7 +132,7 @@ public void testLocalInfileValidInterceptor() throws Exception { @Test public void testLocalInfileUnValidInterceptor() throws Exception { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); File temp = File.createTempFile("localInfile", ".txt"); StringBuilder builder = new StringBuilder(); builder.append("1,hello\n"); @@ -176,7 +183,7 @@ private void testLocalInfile(Connection connection, String file) throws SQLExcep @Test public void loadDataInfileEmpty() throws SQLException, IOException { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); // Create temp file. File temp = File.createTempFile("validateInfile", ".tmp"); try (Connection connection = setConnection("&allowLocalInfile=true")) { @@ -196,7 +203,7 @@ public void loadDataInfileEmpty() throws SQLException, IOException { @Test public void testPrepareLocalInfileWithoutInputStream() throws SQLException { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); try (Connection connection = setConnection("&allowLocalInfile=true")) { try { PreparedStatement st = @@ -283,13 +290,13 @@ private void checkBigLocalInfile(long fileSize) throws Exception { @Test public void testSmallBigLocalInfileInputStream() throws Exception { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); checkBigLocalInfile(256); } @Test public void test2xBigLocalInfileInputStream() throws Exception { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); Assume.assumeTrue(checkMaxAllowedPacketMore40m("test2xBigLocalInfileInputStream")); checkBigLocalInfile(16777216 * 2); @@ -298,7 +305,7 @@ public void test2xBigLocalInfileInputStream() throws Exception { @Test public void testMoreThanMaxAllowedPacketLocalInfileInputStream() throws Exception { Assume.assumeFalse((!isMariadbServer() && minVersion(8, 0, 3))); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeFalse(sharedIsAurora()); Statement stmt = sharedConnection.createStatement(); ResultSet rs = stmt.executeQuery("select @@max_allowed_packet"); diff --git a/src/test/java/org/mariadb/jdbc/MariaDbCompatibilityTest.java b/src/test/java/org/mariadb/jdbc/MariaDbCompatibilityTest.java index 8cd135ce9..832727de2 100644 --- a/src/test/java/org/mariadb/jdbc/MariaDbCompatibilityTest.java +++ b/src/test/java/org/mariadb/jdbc/MariaDbCompatibilityTest.java @@ -55,21 +55,28 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class MariaDbCompatibilityTest extends BaseTest { - /** - * Preparation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("datatypesTest", "type_longvarchar TEXT NULL"); - createTable( - "mysqlcompatibilitytest", "id int not null primary key auto_increment, test bit(1)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE datatypesTest(type_longvarchar TEXT NULL)"); + stmt.execute( + "CREATE TABLE mysqlcompatibilitytest(id int not null primary key auto_increment, test bit(1))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS datatypesTest"); + stmt.execute("DROP TABLE IF EXISTS mysqlcompatibilitytest"); + } } /** diff --git a/src/test/java/org/mariadb/jdbc/MariaDbDatabaseMetaDataTest.java b/src/test/java/org/mariadb/jdbc/MariaDbDatabaseMetaDataTest.java index 04d0ba781..6642a76aa 100644 --- a/src/test/java/org/mariadb/jdbc/MariaDbDatabaseMetaDataTest.java +++ b/src/test/java/org/mariadb/jdbc/MariaDbDatabaseMetaDataTest.java @@ -55,10 +55,28 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; public class MariaDbDatabaseMetaDataTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE yearTableMeta(xx tinyint(1), x2 tinyint(1) unsigned, yy year(4), zz bit, uu smallint)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE yearTableMeta"); + } + } + /** * CONJ-412: tinyInt1isBit and yearIsDateType is not applied in method columnTypeClause. * @@ -66,8 +84,6 @@ public class MariaDbDatabaseMetaDataTest extends BaseTest { */ @Test public void testYearDataType() throws Exception { - createTable( - "yearTableMeta", "xx tinyint(1), x2 tinyint(1) unsigned, yy year(4), zz bit, uu smallint"); try (Connection connection = setConnection()) { checkResults(connection, true, true); } diff --git a/src/test/java/org/mariadb/jdbc/MariaDbPoolDataSourceTest.java b/src/test/java/org/mariadb/jdbc/MariaDbPoolDataSourceTest.java index 928d7cc38..94944e6f1 100644 --- a/src/test/java/org/mariadb/jdbc/MariaDbPoolDataSourceTest.java +++ b/src/test/java/org/mariadb/jdbc/MariaDbPoolDataSourceTest.java @@ -35,13 +35,32 @@ import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.ObjectName; +import org.junit.AfterClass; import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; import org.mariadb.jdbc.internal.util.pool.Pools; import org.mariadb.jdbc.internal.util.scheduler.MariaDbThreadFactory; public class MariaDbPoolDataSourceTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE testResetRollback(id int not null primary key auto_increment, test varchar(20))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS testResetRollback"); + } + } + @Test public void testResetDatabase() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { @@ -221,7 +240,8 @@ public void testResetAutoCommitOption() throws SQLException { @Test public void testResetTransactionIsolation() throws SQLException { - Assume.assumeTrue(!sharedIsAurora() && System.getenv("SKYSQL") == null); + Assume.assumeTrue( + !sharedIsAurora() && System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { @@ -296,7 +316,9 @@ public void testIdleTimeout() throws Throwable { // not for maxscale, testing thread id is not relevant. // appveyor is so slow wait time are not relevant. Assume.assumeTrue( - System.getenv("SKYSQL") == null && System.getenv("APPVEYOR_BUILD_WORKER_IMAGE") == null); + System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null + && System.getenv("APPVEYOR_BUILD_WORKER_IMAGE") == null); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=testIdleTimeout-*"); @@ -386,8 +408,7 @@ public void testJmxDisable() throws Exception { @Test public void testResetRollback() throws SQLException { - createTable( - "testResetRollback", "id int not null primary key auto_increment, test varchar(20)"); + sharedConnection.createStatement().execute("FLUSH TABLES"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { Statement stmt = connection.createStatement(); @@ -407,7 +428,7 @@ public void testResetRollback() throws SQLException { @Test public void ensureUsingPool() throws Exception { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); ThreadPoolExecutor connectionAppender = new ThreadPoolExecutor( 50, diff --git a/src/test/java/org/mariadb/jdbc/MultiTest.java b/src/test/java/org/mariadb/jdbc/MultiTest.java index 046c7e85f..f582d3956 100644 --- a/src/test/java/org/mariadb/jdbc/MultiTest.java +++ b/src/test/java/org/mariadb/jdbc/MultiTest.java @@ -56,53 +56,107 @@ import java.sql.*; import java.util.Properties; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; public class MultiTest extends BaseTest { - /** Tables initialisation. */ @BeforeClass() public static void initClass() throws SQLException { + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE MultiTestt1(id int, test varchar(100))"); + stmt.execute("CREATE TABLE MultiTestt2(id int, test varchar(100))"); + stmt.execute("CREATE TABLE MultiTestt3(message text)"); + stmt.execute("CREATE TABLE MultiTestt4(id int, test varchar(100), PRIMARY KEY (`id`))"); + stmt.execute("CREATE TABLE MultiTestt5(id int, test varchar(100))"); + stmt.execute("CREATE TABLE MultiTestt6(id int, test varchar(100))"); + stmt.execute("CREATE TABLE MultiTestt7(id int, test varchar(100))"); + stmt.execute("CREATE TABLE MultiTestt8(id int, test varchar(100))"); + stmt.execute("CREATE TABLE MultiTestt10(id int)"); + stmt.execute( + "CREATE TABLE MultiTestreWriteDuplicateTestTable(id int, name varchar(100), PRIMARY KEY (`id`))"); + stmt.execute("CREATE TABLE MultiTesttselect1(LAST_UPDATE_DATETIME TIMESTAMP , nn int)"); + stmt.execute("CREATE TABLE MultiTesttselect2(nn int)"); + stmt.execute("CREATE TABLE MultiTesttselect3(LAST_UPDATE_DATETIME TIMESTAMP , nn int)"); + stmt.execute("CREATE TABLE MultiTesttselect4(nn int)"); + stmt.execute( + "CREATE TABLE MultiTestt3_dupp(col1 int, pkey int NOT NULL, col2 int, col3 int, col4 int, PRIMARY KEY (`pkey`))"); + stmt.execute( + "CREATE TABLE MultiTesttest_table(col1 VARCHAR(32), col2 VARCHAR(32), col3 VARCHAR(32), col4 VARCHAR(32), " + + "col5 VARCHAR(32))"); + stmt.execute( + "CREATE TABLE MultiTesttest_table2(col1 VARCHAR(32), col2 VARCHAR(32), col3 VARCHAR(32), col4 VARCHAR(32), " + + "col5 VARCHAR(32))"); + stmt.execute("CREATE TABLE MultiTestValues(col1 VARCHAR(32), col2 VARCHAR(32))"); + stmt.execute( + "CREATE TABLE MultiTestprepsemi(id int not null primary key auto_increment, text text)"); + stmt.execute("CREATE TABLE MultiTestA(data varchar(10))"); + stmt.execute( + "CREATE TABLE testMultiGeneratedKey(id int not null primary key auto_increment, text text)"); + stmt.execute("CREATE TABLE MultiTestt11(id int, test varchar(10000))"); + stmt.execute("CREATE TABLE insertSelectTable1(tt int)"); + stmt.execute("CREATE TABLE insertSelectTable2(tt int)"); + stmt.execute( + "CREATE TABLE SOME_TABLE(ID INT(11) not null, FOO INT(11), PRIMARY KEY (ID), UNIQUE INDEX `FOO` (`FOO`))"); + stmt.execute("CREATE TABLE MultiTestt9(id int not null primary key, test varchar(10))"); + stmt.execute("CREATE TABLE testStatementClose(id int)"); + stmt.execute("CREATE TABLE testPrepareStatementClose(id int)"); + stmt.execute("CREATE TABLE batchUpdateException(i int,PRIMARY KEY (i))"); + stmt.execute("CREATE TABLE testAffectedRow(id int)"); + stmt.execute("CREATE TABLE testAffectedRowBatch(id int PRIMARY KEY, data varchar(10))"); + stmt.execute("CREATE TABLE testInsertSelectBulk(col int, val int)"); + stmt.execute("CREATE TABLE testInsertSelectBulk2(col int, val int)"); + stmt.execute("FLUSH TABLES"); + + if (testSingleHost) { + Statement st = sharedConnection.createStatement(); + st.execute("insert into MultiTestt1 values(1,'a'),(2,'a')"); + st.execute("insert into MultiTestt2 values(1,'a'),(2,'a')"); + st.execute("insert into MultiTestt5 values(1,'a'),(2,'a'),(2,'b')"); + } + stmt.execute("FLUSH TABLES"); + } + } - createTable("MultiTestt1", "id int, test varchar(100)"); - createTable("MultiTestt2", "id int, test varchar(100)"); - createTable("MultiTestt3", "message text"); - createTable("MultiTestt4", "id int, test varchar(100), PRIMARY KEY (`id`)"); - createTable("MultiTestt5", "id int, test varchar(100)"); - createTable("MultiTestt6", "id int, test varchar(100)"); - createTable("MultiTestt7", "id int, test varchar(100)"); - createTable("MultiTestt8", "id int, test varchar(100)"); - createTable("MultiTestt10", "id int"); - createTable( - "MultiTestreWriteDuplicateTestTable", "id int, name varchar(100), PRIMARY KEY (`id`)"); - createTable("MultiTesttselect1", "LAST_UPDATE_DATETIME TIMESTAMP , nn int"); - createTable("MultiTesttselect2", "nn int"); - createTable("MultiTesttselect3", "LAST_UPDATE_DATETIME TIMESTAMP , nn int"); - createTable("MultiTesttselect4", "nn int"); - createTable( - "MultiTestt3_dupp", - "col1 int, pkey int NOT NULL, col2 int, col3 int, col4 int, PRIMARY KEY " + "(`pkey`)"); - createTable( - "MultiTesttest_table", - "col1 VARCHAR(32), col2 VARCHAR(32), col3 VARCHAR(32), col4 VARCHAR(32), " - + "col5 VARCHAR(32)"); - createTable( - "MultiTesttest_table2", - "col1 VARCHAR(32), col2 VARCHAR(32), col3 VARCHAR(32), col4 VARCHAR(32), " - + "col5 VARCHAR(32)"); - createTable("MultiTestValues", "col1 VARCHAR(32), col2 VARCHAR(32)"); - - createTable("MultiTestprepsemi", "id int not null primary key auto_increment, text text"); - createTable("MultiTestA", "data varchar(10)"); - createTable("testMultiGeneratedKey", "id int not null primary key auto_increment, text text"); - - if (testSingleHost) { - Statement st = sharedConnection.createStatement(); - st.execute("insert into MultiTestt1 values(1,'a'),(2,'a')"); - st.execute("insert into MultiTestt2 values(1,'a'),(2,'a')"); - st.execute("insert into MultiTestt5 values(1,'a'),(2,'a'),(2,'b')"); + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS testInsertSelectBulk"); + stmt.execute("DROP TABLE IF EXISTS testInsertSelectBulk2"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt1"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt2"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt3"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt4"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt5"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt6"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt7"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt8"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt10"); + stmt.execute("DROP TABLE IF EXISTS MultiTestreWriteDuplicateTestTable"); + stmt.execute("DROP TABLE IF EXISTS MultiTesttselect1"); + stmt.execute("DROP TABLE IF EXISTS MultiTesttselect2"); + stmt.execute("DROP TABLE IF EXISTS MultiTesttselect3"); + stmt.execute("DROP TABLE IF EXISTS MultiTesttselect4"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt3_dupp"); + stmt.execute("DROP TABLE IF EXISTS MultiTesttest_table"); + stmt.execute("DROP TABLE IF EXISTS MultiTesttest_table2"); + stmt.execute("DROP TABLE IF EXISTS MultiTestValues"); + stmt.execute("DROP TABLE IF EXISTS MultiTestprepsemi"); + stmt.execute("DROP TABLE IF EXISTS MultiTestA"); + stmt.execute("DROP TABLE IF EXISTS testMultiGeneratedKey"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt11"); + stmt.execute("DROP TABLE IF EXISTS insertSelectTable1"); + stmt.execute("DROP TABLE IF EXISTS insertSelectTable2"); + stmt.execute("DROP TABLE IF EXISTS SOME_TABLE"); + stmt.execute("DROP TABLE IF EXISTS MultiTestt9"); + stmt.execute("DROP TABLE IF EXISTS testStatementClose"); + stmt.execute("DROP TABLE IF EXISTS testPrepareStatementClose"); + stmt.execute("DROP TABLE IF EXISTS batchUpdateException"); + stmt.execute("DROP TABLE IF EXISTS testAffectedRow"); + stmt.execute("DROP TABLE IF EXISTS testAffectedRowBatch"); } } @@ -297,7 +351,7 @@ public void setMaxRowsMulti() throws Exception { */ @Test public void rewriteBatchedStatementsDisabledInsertionTest() throws SQLException { - verifyInsertBehaviorBasedOnRewriteBatchedStatements(Boolean.FALSE, 3000); + verifyInsertBehaviorBasedOnRewriteBatchedStatements(Boolean.FALSE, 3000, "MultiTestt6"); } /** @@ -307,8 +361,6 @@ public void rewriteBatchedStatementsDisabledInsertionTest() throws SQLException */ @Test public void rewriteBatchedMaxAllowedSizeTest() throws SQLException { - - createTable("MultiTestt6", "id int, test varchar(10000)"); Assume.assumeTrue(checkMaxAllowedPacketMore8m("rewriteBatchedMaxAllowedSizeTest")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@max_allowed_packet"); @@ -316,7 +368,8 @@ public void rewriteBatchedMaxAllowedSizeTest() throws SQLException { long maxAllowedPacket = rs.getInt(1); Assume.assumeTrue(maxAllowedPacket < 512 * 1024 * 1024L); int totalInsertCommands = (int) Math.ceil(maxAllowedPacket / 10050); - verifyInsertBehaviorBasedOnRewriteBatchedStatements(Boolean.TRUE, totalInsertCommands); + verifyInsertBehaviorBasedOnRewriteBatchedStatements( + Boolean.TRUE, totalInsertCommands, "MultiTestt11"); } else { fail(); } @@ -388,8 +441,6 @@ private void checkResult(PreparedStatement statement) throws SQLException { @Test public void testServerPrepareMeta() throws Throwable { try (Connection connection = setConnection("&rewriteBatchedStatements=true")) { - createTable("insertSelectTable1", "tt int"); - createTable("insertSelectTable2", "tt int"); Statement stmt = connection.createStatement(); stmt.execute("INSERT INTO insertSelectTable2(tt) VALUES (1),(2),(1)"); @@ -411,7 +462,8 @@ public void testServerPrepareMeta() throws Throwable { } private void verifyInsertBehaviorBasedOnRewriteBatchedStatements( - Boolean rewriteBatchedStatements, int totalInsertCommands) throws SQLException { + Boolean rewriteBatchedStatements, int totalInsertCommands, String tableName) + throws SQLException { Properties props = new Properties(); props.setProperty("rewriteBatchedStatements", rewriteBatchedStatements.toString()); props.setProperty("allowMultiQueries", "true"); @@ -419,7 +471,8 @@ private void verifyInsertBehaviorBasedOnRewriteBatchedStatements( verifyInsertCount(tmpConnection, 0); Statement statement = tmpConnection.createStatement(); for (int i = 0; i < totalInsertCommands; i++) { - statement.addBatch("INSERT INTO MultiTestt6 VALUES (" + i + ", 'testValue" + i + "')"); + statement.addBatch( + "INSERT INTO " + tableName + " VALUES (" + i + ", 'testValue" + i + "')"); } int[] updateCounts = statement.executeBatch(); assertEquals(totalInsertCommands, updateCounts.length); @@ -792,9 +845,6 @@ public void testInsertWithoutFirstContent() throws Exception { @Test public void testduplicate() throws Exception { - createTable( - "SOME_TABLE", - "ID INT(11) not null, FOO INT(11), PRIMARY KEY (ID), UNIQUE INDEX `FOO` (`FOO`)"); String sql = "insert into `SOME_TABLE` (`ID`, `FOO`) values (?, ?) " + "on duplicate key update `SOME_TABLE`.`FOO` = ?"; @@ -874,18 +924,8 @@ public void continueOnBatchError() throws SQLException { private void continueOnBatchError( boolean continueBatch, boolean serverPrepare, boolean rewrite, boolean batchMulti) throws SQLException { - System.out.println( - "continueBatch:" - + continueBatch - + " serverPrepare:" - + serverPrepare - + " rewrite:" - + rewrite - + " batchMulti:" - + batchMulti); - createTable("MultiTestt9", "id int not null primary key, test varchar(10)"); Assume.assumeTrue(!batchMulti || !sharedIsAurora()); - + sharedConnection.createStatement().execute("TRUNCATE MultiTestt9"); try (Connection connection = setBlankConnection( "&useServerPrepStmts=" @@ -999,7 +1039,6 @@ public void testClosePrepareStatementWithoutQuery() throws SQLException { @Test public void testCloseStatement() throws SQLException { - createTable("testStatementClose", "id int"); final Statement statement = sharedConnection.createStatement(); // Make sure it is a streaming statement: statement.setFetchSize(1); @@ -1012,7 +1051,6 @@ public void testCloseStatement() throws SQLException { @Test public void testClosePrepareStatement() throws SQLException { - createTable("testPrepareStatementClose", "id int"); sharedConnection .createStatement() .execute("INSERT INTO testPrepareStatementClose(id) VALUES (1),(2),(3)"); @@ -1044,13 +1082,11 @@ public void rewriteErrorStandard() throws SQLException { private void prepareBatchUpdateException( Boolean rewriteBatchedStatements, Boolean allowMultiQueries) throws SQLException { - - createTable("batchUpdateException", "i int,PRIMARY KEY (i)"); Properties props = new Properties(); props.setProperty("rewriteBatchedStatements", rewriteBatchedStatements.toString()); props.setProperty("allowMultiQueries", allowMultiQueries.toString()); props.setProperty("useServerPrepStmts", "false"); - + sharedConnection.createStatement().execute("TRUNCATE batchUpdateException"); try (Connection tmpConnection = openNewConnection(connUri, props)) { verifyInsertCount(tmpConnection, 0); @@ -1070,6 +1106,7 @@ private void prepareBatchUpdateException( fail("exception should be throw above"); } catch (BatchUpdateException bue) { int[] updateCounts = bue.getUpdateCounts(); + if (rewriteBatchedStatements || (sharedOptions().useBulkStmts && isMariadbServer() && minVersion(10, 2))) { assertEquals(4, updateCounts.length); @@ -1327,12 +1364,8 @@ private void checkResults(Connection connection) throws SQLException { @Test public void testInsertSelectBulk() throws SQLException { - try (Statement statement = sharedConnection.createStatement()) { - statement.execute("DROP TABLE IF EXISTS testInsertSelectBulk"); - statement.execute("DROP TABLE IF EXISTS testInsertSelectBulk2"); - statement.execute("CREATE TABLE testInsertSelectBulk(col int, val int)"); - statement.execute("CREATE TABLE testInsertSelectBulk2(col int, val int)"); - statement.execute("INSERT INTO testInsertSelectBulk(col, val) VALUES (0,1), (2,3)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("INSERT INTO testInsertSelectBulk(col, val) VALUES (0,1), (2,3)"); try (PreparedStatement preparedStatement = sharedConnection.prepareStatement( @@ -1350,7 +1383,7 @@ public void testInsertSelectBulk() throws SQLException { preparedStatement.executeBatch(); } - ResultSet rs = statement.executeQuery("SELECT * from testInsertSelectBulk2"); + ResultSet rs = stmt.executeQuery("SELECT * from testInsertSelectBulk2"); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals(1, rs.getInt(2)); @@ -1363,7 +1396,6 @@ public void testInsertSelectBulk() throws SQLException { @Test public void testAffectedRow() throws SQLException { - createTable("testAffectedRow", "id int"); testAffectedRow(false); testAffectedRow(true); } @@ -1517,7 +1549,6 @@ public void multiInsertReturnOneGeneratedOnDuplicateMultiple() throws Throwable @Test public void testAffectedRowBatch() throws SQLException { - createTable("testAffectedRowBatch", "id int PRIMARY KEY, data varchar(10)"); testAffectedRowBatch(false); testAffectedRowBatch(true); diff --git a/src/test/java/org/mariadb/jdbc/ParserTest.java b/src/test/java/org/mariadb/jdbc/ParserTest.java index 242d71b5d..a43398001 100644 --- a/src/test/java/org/mariadb/jdbc/ParserTest.java +++ b/src/test/java/org/mariadb/jdbc/ParserTest.java @@ -57,6 +57,7 @@ import java.sql.*; import java.util.ArrayList; import java.util.Properties; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -65,15 +66,21 @@ public class ParserTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("table1", "id1 int auto_increment primary key"); - createTable("table2", "id2 int auto_increment primary key"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE table1(id1 int auto_increment primary key)"); + stmt.execute("CREATE TABLE table2(id2 int auto_increment primary key)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS table1"); + stmt.execute("DROP TABLE IF EXISTS table2"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/PasswordEncodingTest.java b/src/test/java/org/mariadb/jdbc/PasswordEncodingTest.java index 90d66e07b..f3c71fb76 100644 --- a/src/test/java/org/mariadb/jdbc/PasswordEncodingTest.java +++ b/src/test/java/org/mariadb/jdbc/PasswordEncodingTest.java @@ -141,7 +141,7 @@ private void createUser(String charsetName, String serverCharset) throws Excepti useOldNotation = false; } if (useOldNotation) { - stmt.execute("CREATE USER 'test" + charsetName + "'@'%'"); + stmt.execute("CREATE USER IF NOT EXISTS 'test" + charsetName + "'@'%'"); stmt.testExecute( "GRANT SELECT on *.* to 'test" + charsetName @@ -176,7 +176,11 @@ private void checkConnection(String charsetName, String[] charsets) throws Excep + "&password=" + exoticPwd + "&passwordCharacterEncoding=" - + currentCharsetName)) { + + currentCharsetName + + ((options.useSsl != null) ? "&useSsl=" + options.useSsl : "") + + ((options.serverSslCert != null) + ? "&serverSslCert=" + options.serverSslCert + : ""))) { if (!currentCharsetName.equals(charsetName)) { fail( "must have failed for charsetName=" diff --git a/src/test/java/org/mariadb/jdbc/PooledConnectionTest.java b/src/test/java/org/mariadb/jdbc/PooledConnectionTest.java index 921f36dfe..cd3f92f84 100644 --- a/src/test/java/org/mariadb/jdbc/PooledConnectionTest.java +++ b/src/test/java/org/mariadb/jdbc/PooledConnectionTest.java @@ -88,7 +88,7 @@ public void testPooledConnectionClosed() throws Exception { @Test(expected = SQLException.class) public void testPooledConnectionException() throws Exception { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); ConnectionPoolDataSource ds = new MariaDbDataSource(hostname != null ? hostname : "localhost", port, database); diff --git a/src/test/java/org/mariadb/jdbc/PreparedStatementTest.java b/src/test/java/org/mariadb/jdbc/PreparedStatementTest.java index da8e917a2..ff96b4398 100644 --- a/src/test/java/org/mariadb/jdbc/PreparedStatementTest.java +++ b/src/test/java/org/mariadb/jdbc/PreparedStatementTest.java @@ -56,6 +56,7 @@ import java.math.BigInteger; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -65,33 +66,57 @@ public class PreparedStatementTest extends BaseTest { private static final int ER_NO_SUCH_TABLE = 1146; private static final String ER_NO_SUCH_TABLE_STATE = "42S02"; - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("table1", "id1 int auto_increment primary key"); - createTable("table2", "id2 int auto_increment primary key"); - createTable( - "`testBigintTable`", - "`id` bigint(20) unsigned NOT NULL, PRIMARY KEY (`id`)", - "ENGINE=InnoDB DEFAULT CHARSET=utf8"); - createTable( - "`backTicksPreparedStatements`", - "`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY," - + "`SLIndex#orBV#` text," - + "`isM&M'sTasty?` bit(1) DEFAULT NULL," - + "`Seems:LikeParam?` bit(1) DEFAULT NULL," - + "`Webinar10-TM/ProjComp` text", - "ENGINE=InnoDB DEFAULT CHARSET=utf8"); - createTable("test_insert_select", "`field1` varchar(20)"); - createTable("test_decimal_insert", "`field1` decimal(10, 7)"); - createTable( - "PreparedStatementTest1", "id int not null primary key auto_increment, test longblob"); - createTable("PreparedStatementTest2", "my_col varchar(20)"); - createTable("PreparedStatementTest3", "my_col varchar(20)"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE table1(id1 int auto_increment primary key)"); + stmt.execute("CREATE TABLE table2(id2 int auto_increment primary key)"); + stmt.execute( + "CREATE TABLE `testBigintTable`(`id` bigint(20) unsigned NOT NULL, PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8"); + stmt.execute( + "CREATE TABLE `backTicksPreparedStatements`(`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY," + + "`SLIndex#orBV#` text," + + "`isM&M'sTasty?` bit(1) DEFAULT NULL," + + "`Seems:LikeParam?` bit(1) DEFAULT NULL," + + "`Webinar10-TM/ProjComp` text) " + + "ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.execute("CREATE TABLE test_insert_select(`field1` varchar(20))"); + stmt.execute("CREATE TABLE test_decimal_insert(`field1` decimal(10, 7))"); + stmt.execute( + "CREATE TABLE PreparedStatementTest1(id int not null primary key auto_increment, test longblob)"); + stmt.execute("CREATE TABLE PreparedStatementTest2(my_col varchar(20))"); + stmt.execute("CREATE TABLE PreparedStatementTest3(my_col varchar(20))"); + stmt.execute( + "CREATE TABLE clientPrepareStatementValuesWithoutParameter(created_at datetime primary key)"); + stmt.execute( + "CREATE TABLE testFallbackPrepare(`test` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL)" + + " ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + stmt.execute( + "CREATE TABLE largePrepareUpdate(a int not null primary key auto_increment, t varchar(256))"); + stmt.execute( + "CREATE TABLE testInsertSelectBulk(v1 varchar(10), v2 varchar(10), v3 varchar(10), v4 varchar(10))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS testInsertSelectBulk"); + stmt.execute("DROP TABLE IF EXISTS table1"); + stmt.execute("DROP TABLE IF EXISTS table2"); + stmt.execute("DROP TABLE IF EXISTS `testBigintTable`"); + stmt.execute("DROP TABLE IF EXISTS `backTicksPreparedStatements`"); + stmt.execute("DROP TABLE IF EXISTS test_insert_select"); + stmt.execute("DROP TABLE IF EXISTS test_decimal_insert"); + stmt.execute("DROP TABLE IF EXISTS PreparedStatementTest1"); + stmt.execute("DROP TABLE IF EXISTS PreparedStatementTest2"); + stmt.execute("DROP TABLE IF EXISTS PreparedStatementTest3"); + stmt.execute("DROP TABLE IF EXISTS clientPrepareStatementValuesWithoutParameter"); + stmt.execute("DROP TABLE IF EXISTS testFallbackPrepare"); + stmt.execute("DROP TABLE IF EXISTS largePrepareUpdate"); + } } @Test @@ -292,10 +317,7 @@ public void testExecuteBatch() throws SQLException { */ @Test public void testFallbackPrepare() throws SQLException { - createTable( - "testFallbackPrepare", - "`test` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL", - "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + try (Connection connection = setConnection()) { Statement stmt = connection.createStatement(); stmt.execute("SET @@character_set_connection = 'utf8mb4'"); @@ -501,8 +523,6 @@ public void clientPrepareStatementWithoutParameter() throws Throwable { */ @Test public void clientPrepareStatementValuesWithoutParameter() throws Throwable { - createTable("clientPrepareStatementValuesWithoutParameter", "created_at datetime primary key"); - String query = "ALTER table clientPrepareStatementValuesWithoutParameter PARTITION BY RANGE COLUMNS( created_at ) " + "(PARTITION test_p201605 VALUES LESS THAN ('2016-06-01'))"; @@ -548,11 +568,7 @@ public void testInsertSelectBulk() throws SQLException { cancelForVersion(10, 3, 3); cancelForVersion(10, 3, 4); - try (Statement statement = sharedConnection.createStatement()) { - statement.execute("DROP TABLE IF EXISTS myTable"); - statement.execute( - "CREATE TABLE myTable(v1 varchar(10), v2 varchar(10), v3 varchar(10), v4 varchar(10))"); - + try (Statement stmt = sharedConnection.createStatement()) { String[][] val = { {null, "b1", "c1", "d1"}, {"a2", null, "c2", "d2"}, @@ -561,7 +577,8 @@ public void testInsertSelectBulk() throws SQLException { {"a5", "b5", "c5", "d5"} }; try (PreparedStatement preparedStatement = - sharedConnection.prepareStatement("INSERT INTO myTable VALUES (?, ?, ?, ?)")) { + sharedConnection.prepareStatement( + "INSERT INTO testInsertSelectBulk VALUES (?, ?, ?, ?)")) { for (int i = 0; i < val.length; i++) { for (int j = 0; j < 4; j++) { preparedStatement.setString(j + 1, val[i][j]); @@ -571,7 +588,7 @@ public void testInsertSelectBulk() throws SQLException { preparedStatement.executeBatch(); } - ResultSet rs = statement.executeQuery("SELECT * from myTable"); + ResultSet rs = stmt.executeQuery("SELECT * from testInsertSelectBulk"); for (int i = 0; i < val.length; i++) { assertTrue(rs.next()); for (int j = 0; j < 4; j++) { @@ -587,10 +604,6 @@ public void testInsertSelectBulk() throws SQLException { @Test public void largePrepareUpdate() throws SQLException { - createTable( - "largePrepareUpdate", - "a int not null primary key auto_increment, t varchar(256)", - "engine=innodb"); try (PreparedStatement stmt = sharedConnection.prepareStatement( "insert into largePrepareUpdate(t) values(?)", Statement.RETURN_GENERATED_KEYS)) { diff --git a/src/test/java/org/mariadb/jdbc/RePrepareTest.java b/src/test/java/org/mariadb/jdbc/RePrepareTest.java index 9e67417e5..e9f583def 100644 --- a/src/test/java/org/mariadb/jdbc/RePrepareTest.java +++ b/src/test/java/org/mariadb/jdbc/RePrepareTest.java @@ -58,14 +58,34 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; public class RePrepareTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE rePrepareTestSelectError(test int)"); + stmt.execute("CREATE TABLE rePrepareTestInsertError(test int)"); + stmt.execute("CREATE TABLE cannotRePrepare(test int)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS rePrepareTestSelectError"); + stmt.execute("DROP TABLE IF EXISTS rePrepareTestInsertError"); + stmt.execute("DROP TABLE IF EXISTS cannotRePrepare"); + } + } + @Test public void rePrepareTestSelectError() throws SQLException { - createTable("rePrepareTestSelectError", "test int"); try (Statement stmt = sharedConnection.createStatement()) { stmt.execute("INSERT INTO rePrepareTestSelectError(test) VALUES (1)"); try (PreparedStatement preparedStatement = @@ -93,7 +113,6 @@ public void rePrepareTestSelectError() throws SQLException { public void rePrepareTestInsertError() throws SQLException { Assume.assumeFalse(sharedIsAurora()); // Aurora has not "flush tables with read lock" right; Assume.assumeFalse(!isMariadbServer() && minVersion(8, 0, 0)); // froze when flush - createTable("rePrepareTestInsertError", "test int"); try (Statement stmt = sharedConnection.createStatement()) { try (PreparedStatement preparedStatement = sharedConnection.prepareStatement( @@ -124,7 +143,6 @@ public void rePrepareTestInsertError() throws SQLException { @Test public void cannotRePrepare() throws SQLException { - createTable("cannotRePrepare", "test int"); try (Statement stmt = sharedConnection.createStatement()) { try (PreparedStatement preparedStatement = sharedConnection.prepareStatement("INSERT INTO cannotRePrepare(test) values (?)")) { diff --git a/src/test/java/org/mariadb/jdbc/ReconnectionStateMaxAllowedStatement.java b/src/test/java/org/mariadb/jdbc/ReconnectionStateMaxAllowedStatement.java index 24ab1135e..565114a78 100644 --- a/src/test/java/org/mariadb/jdbc/ReconnectionStateMaxAllowedStatement.java +++ b/src/test/java/org/mariadb/jdbc/ReconnectionStateMaxAllowedStatement.java @@ -54,15 +54,30 @@ import static org.junit.Assert.*; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.Arrays; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; public class ReconnectionStateMaxAllowedStatement extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE foo (x longblob)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS foo"); + } + } + @Test public void isolationLevelResets() throws SQLException { try (Connection connection = setConnection()) { @@ -70,7 +85,6 @@ public void isolationLevelResets() throws SQLException { if (max > Integer.MAX_VALUE - 10) { fail("max_allowed_packet too high for this test"); } - connection.prepareStatement("create table if not exists foo (x longblob)").execute(); connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); assertEquals("READ-UNCOMMITTED", level((MariaDbConnection) connection)); diff --git a/src/test/java/org/mariadb/jdbc/ResultSetMetaDataTest.java b/src/test/java/org/mariadb/jdbc/ResultSetMetaDataTest.java index bfaa12069..66aa4e978 100644 --- a/src/test/java/org/mariadb/jdbc/ResultSetMetaDataTest.java +++ b/src/test/java/org/mariadb/jdbc/ResultSetMetaDataTest.java @@ -25,25 +25,37 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class ResultSetMetaDataTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "test_rsmd", - "id_col int not null primary key auto_increment, " - + "nullable_col varchar(20),unikey_col int unique, char_col char(10), us smallint unsigned"); - createTable("t1", "id int, name varchar(20)"); - createTable("t2", "id int, name varchar(20)"); - createTable("t3", "id int, name varchar(20)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE test_rsmd(id_col int not null primary key auto_increment, " + + "nullable_col varchar(20),unikey_col int unique, char_col char(10), us smallint unsigned)"); + stmt.execute("CREATE TABLE t1(id int, name varchar(20))"); + stmt.execute("CREATE TABLE t2(id int, name varchar(20))"); + stmt.execute("CREATE TABLE t3(id int, name varchar(20))"); + stmt.execute("CREATE TABLE testAlias(id int, name varchar(20))"); + stmt.execute("CREATE TABLE testAlias2(id2 int, name2 varchar(20))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS test_rsmd"); + stmt.execute("DROP TABLE IF EXISTS t1"); + stmt.execute("DROP TABLE IF EXISTS t2"); + stmt.execute("DROP TABLE IF EXISTS t3"); + stmt.execute("DROP TABLE IF EXISTS testAlias"); + stmt.execute("DROP TABLE IF EXISTS testAlias2"); + } } @Test @@ -157,8 +169,6 @@ public void conj84() throws Exception { @Test public void testAlias() throws Exception { - createTable("testAlias", "id int, name varchar(20)"); - createTable("testAlias2", "id2 int, name2 varchar(20)"); Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO testAlias VALUES (1, 'foo')"); diff --git a/src/test/java/org/mariadb/jdbc/ResultSetTest.java b/src/test/java/org/mariadb/jdbc/ResultSetTest.java index dccb2a934..441f5108d 100644 --- a/src/test/java/org/mariadb/jdbc/ResultSetTest.java +++ b/src/test/java/org/mariadb/jdbc/ResultSetTest.java @@ -55,21 +55,98 @@ import static org.junit.Assert.*; import java.sql.*; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; public class ResultSetTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("result_set_test", "id int not null primary key auto_increment, name char(20)"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE result_set_test(id int not null primary key auto_increment, name char(20))"); + stmt.execute( + "CREATE TABLE gen_key_test_resultset(name VARCHAR(40) NOT NULL, xml MEDIUMTEXT)"); + stmt.execute( + "CREATE TABLE columnNamesMappingError(xX INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(xX))"); + if (isMariadbServer() && minVersion(10, 3)) { + stmt.execute( + "CREATE TABLE checkInvisibleMetaData(xx tinyint(1), x2 tinyint(1) unsigned INVISIBLE primary key auto_increment, yy year(4), zz bit, uu smallint)"); + stmt.execute( + "CREATE TABLE invisible(x INT, y INT INVISIBLE, z INT INVISIBLE NOT NULL DEFAULT 4)"); + } + stmt.execute("CREATE TABLE doubleStringResults(i double, j float)"); + stmt.execute("CREATE TABLE testStreamInsensitive(s1 varchar(20))"); + stmt.execute( + "CREATE TABLE generatedKeyNpe(id int not null primary key auto_increment, val int)"); + stmt.execute("CREATE TABLE testStreamForward(s1 varchar(20))"); + stmt.execute( + "CREATE TABLE leadingZero(" + + "t1 TINYINT(3) unsigned zerofill" + + ", t2 TINYINT(8) unsigned zerofill" + + ", t3 TINYINT unsigned zerofill" + + ", t4 smallint(3) unsigned zerofill" + + ", t5 smallint(8) unsigned zerofill" + + ", t6 smallint unsigned zerofill" + + ", t7 MEDIUMINT(3) unsigned zerofill" + + ", t8 MEDIUMINT(8) unsigned zerofill" + + ", t9 MEDIUMINT unsigned zerofill" + + ", t10 INT(3) unsigned zerofill" + + ", t11 INT(8) unsigned zerofill" + + ", t12 INT unsigned zerofill" + + ", t13 BIGINT(3) unsigned zerofill" + + ", t14 BIGINT(8) unsigned zerofill" + + ", t15 BIGINT unsigned zerofill" + + ", t16 DECIMAL(6,3) unsigned zerofill" + + ", t17 DECIMAL(11,3) unsigned zerofill" + + ", t18 DECIMAL unsigned zerofill" + + ", t19 FLOAT(6,3) unsigned zerofill" + + ", t20 FLOAT(11,3) unsigned zerofill" + + ", t21 FLOAT unsigned zerofill" + + ", t22 DOUBLE(6,3) unsigned zerofill" + + ", t23 DOUBLE(11,3) unsigned zerofill" + + ", t24 DOUBLE unsigned zerofill)"); + stmt.execute( + "CREATE TABLE numericTypeTable(" + + "t1 tinyint, " + + "t2 boolean, " + + "t3 smallint, " + + "t4 mediumint, " + + "t5 int, " + + "t6 bigint, " + + "t7 decimal, " + + "t8 float, " + + "t9 double, " + + "t10 bit," + + "t11 char(10)," + + "t12 varchar(10)," + + "t13 binary(10)," + + "t14 varbinary(10)," + + "t15 text," + + "t16 blob," + + "t17 date)"); + stmt.execute( + "CREATE TABLE nullField(t1 varchar(50), t2 timestamp NULL, t3 date, t4 year(4))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS result_set_test"); + stmt.execute("DROP TABLE IF EXISTS gen_key_test_resultset"); + stmt.execute("DROP TABLE IF EXISTS columnNamesMappingError"); + stmt.execute("DROP TABLE IF EXISTS checkInvisibleMetaData"); + stmt.execute("DROP TABLE IF EXISTS invisible"); + stmt.execute("DROP TABLE IF EXISTS doubleStringResults"); + stmt.execute("DROP TABLE IF EXISTS testStreamInsensitive"); + stmt.execute("DROP TABLE IF EXISTS generatedKeyNpe"); + stmt.execute("DROP TABLE IF EXISTS testStreamForward"); + stmt.execute("DROP TABLE IF EXISTS leadingZero"); + stmt.execute("DROP TABLE IF EXISTS numericTypeTable"); + stmt.execute("DROP TABLE IF EXISTS nullField"); + } } @Test @@ -99,7 +176,6 @@ public void isBeforeFirstFetchTest() throws SQLException { */ @Test public void testGeneratedKeysWithoutTableAutoIncrementCalledTwice() throws SQLException { - createTable("gen_key_test_resultset", "name VARCHAR(40) NOT NULL, xml MEDIUMTEXT"); String sql = "INSERT INTO gen_key_test_resultset (name, xml) VALUES (?, ?)"; for (int i = 0; i < 2; i++) { @@ -515,7 +591,6 @@ private void insertRows(int numberOfRowsToInsert) throws SQLException { */ @Test public void generatedKeyNpe() throws SQLException { - createTable("generatedKeyNpe", "id int not null primary key auto_increment, val int"); Statement statement = sharedConnection.createStatement(); statement.execute( "INSERT INTO generatedKeyNpe(val) values (0)", Statement.RETURN_GENERATED_KEYS); @@ -526,7 +601,6 @@ public void generatedKeyNpe() throws SQLException { @Test public void generatedKeyError() throws SQLException { - createTable("generatedKeyNpe", "id int not null primary key auto_increment, val int"); Statement statement = sharedConnection.createStatement(); statement.execute("INSERT INTO generatedKeyNpe(val) values (0)"); try { @@ -639,7 +713,6 @@ private void checkLastResultSet(Statement statement) throws SQLException { @Test public void testStreamInsensitive() throws Exception { - createTable("testStreamInsensitive", "s1 varchar(20)"); for (int r = 0; r < 20; r++) { sharedConnection @@ -696,7 +769,6 @@ public void testStreamInsensitive() throws Exception { @Test public void testStreamForward() throws Exception { - createTable("testStreamForward", "s1 varchar(20)"); for (int r = 0; r < 20; r++) { sharedConnection @@ -759,32 +831,6 @@ public void testStreamForward() throws Exception { */ @Test public void leadingZeroTest() throws SQLException { - createTable( - "leadingZero", - "t1 TINYINT(3) unsigned zerofill" - + ", t2 TINYINT(8) unsigned zerofill" - + ", t3 TINYINT unsigned zerofill" - + ", t4 smallint(3) unsigned zerofill" - + ", t5 smallint(8) unsigned zerofill" - + ", t6 smallint unsigned zerofill" - + ", t7 MEDIUMINT(3) unsigned zerofill" - + ", t8 MEDIUMINT(8) unsigned zerofill" - + ", t9 MEDIUMINT unsigned zerofill" - + ", t10 INT(3) unsigned zerofill" - + ", t11 INT(8) unsigned zerofill" - + ", t12 INT unsigned zerofill" - + ", t13 BIGINT(3) unsigned zerofill" - + ", t14 BIGINT(8) unsigned zerofill" - + ", t15 BIGINT unsigned zerofill" - + ", t16 DECIMAL(6,3) unsigned zerofill" - + ", t17 DECIMAL(11,3) unsigned zerofill" - + ", t18 DECIMAL unsigned zerofill" - + ", t19 FLOAT(6,3) unsigned zerofill" - + ", t20 FLOAT(11,3) unsigned zerofill" - + ", t21 FLOAT unsigned zerofill" - + ", t22 DOUBLE(6,3) unsigned zerofill" - + ", t23 DOUBLE(11,3) unsigned zerofill" - + ", t24 DOUBLE unsigned zerofill"); Statement stmt = sharedConnection.createStatement(); stmt.executeUpdate( "insert into leadingZero values (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1), " @@ -906,26 +952,6 @@ public void firstForwardTest() throws SQLException { */ @Test public void testNumericType() throws SQLException { - createTable( - "numericTypeTable", - "t1 tinyint, " - + "t2 boolean, " - + "t3 smallint, " - + "t4 mediumint, " - + "t5 int, " - + "t6 bigint, " - + "t7 decimal, " - + "t8 float, " - + "t9 double, " - + "t10 bit," - + "t11 char(10)," - + "t12 varchar(10)," - + "t13 binary(10)," - + "t14 varbinary(10)," - + "t15 text," - + "t16 blob," - + "t17 date"); - try (Statement stmt = sharedConnection.createStatement()) { stmt.execute( "INSERT into numericTypeTable values (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 'a', 'a', 'a', 'a', 'a', 'a', now())"); @@ -1040,7 +1066,6 @@ public void numericTestWithDecimal() throws SQLException { @Test public void nullField() throws SQLException { Assume.assumeTrue(isMariadbServer()); // '0000-00-00' doesn't work anymore on mysql 5.7. - createTable("nullField", "t1 varchar(50), t2 timestamp NULL, t3 date, t4 year(4)"); Statement stmt = sharedConnection.createStatement(); stmt.execute( "INSERT INTO nullField(t1,t2,t3,t4) values " @@ -1119,7 +1144,6 @@ public void nullField() throws SQLException { @Test public void doubleStringResults() throws SQLException { - createTable("doubleStringResults", "i double, j float"); Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO doubleStringResults VALUES (1.1, 1.2), (23, 24)"); ResultSet rs = stmt.executeQuery("SELECT * FROM doubleStringResults"); @@ -1149,8 +1173,6 @@ public void invisibleColumn() throws SQLException { cancelForVersion(10, 3, 0); cancelForVersion(10, 3, 1); cancelForVersion(10, 3, 2); - - createTable("invisible", "x INT, y INT INVISIBLE, z INT INVISIBLE NOT NULL DEFAULT 4"); Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO invisible(x,y) VALUES (1,2)"); @@ -1178,10 +1200,6 @@ public void checkInvisibleMetaData() throws SQLException { cancelForVersion(10, 3, 0); cancelForVersion(10, 3, 1); cancelForVersion(10, 3, 2); - - createTable( - "checkInvisibleMetaData", - "xx tinyint(1), x2 tinyint(1) unsigned INVISIBLE primary key auto_increment, yy year(4), zz bit, uu smallint"); DatabaseMetaData meta = sharedConnection.getMetaData(); ResultSet rs = meta.getColumns(null, null, "checkInvisibleMetaData", null); assertTrue(rs.next()); @@ -1196,14 +1214,12 @@ public void checkInvisibleMetaData() throws SQLException { @Test public void columnNamesMappingError() throws SQLException { - createTable( - "columnNamesMappingError", "xX INT NOT NULL AUTO_INCREMENT, " + " PRIMARY KEY(xX)"); Statement stmt = sharedConnection.createStatement(); stmt.executeUpdate("INSERT INTO columnNamesMappingError VALUES (4)"); try (PreparedStatement preparedStatement = sharedConnection.prepareStatement( - "SELECT * FROM " + "columnNamesMappingError", + "SELECT * FROM columnNamesMappingError", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { ResultSet rs = preparedStatement.executeQuery(); diff --git a/src/test/java/org/mariadb/jdbc/ScalarFunctionsTest.java b/src/test/java/org/mariadb/jdbc/ScalarFunctionsTest.java index 078e7da72..88aa7d8b0 100644 --- a/src/test/java/org/mariadb/jdbc/ScalarFunctionsTest.java +++ b/src/test/java/org/mariadb/jdbc/ScalarFunctionsTest.java @@ -31,10 +31,33 @@ import java.math.BigInteger; import java.sql.*; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; public class ScalarFunctionsTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE TEST_SYNTAX_ERROR(" + + " id INTEGER unsigned NOT NULL AUTO_INCREMENT, " + + " str_value MEDIUMTEXT CHARACTER SET utf8mb4 NOT NULL," + + " json_value MEDIUMTEXT CHARACTER SET utf8mb4 NOT NULL, " + + " PRIMARY KEY ( id ))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS TEST_SYNTAX_ERROR"); + } + } + @Test public void nativeSqlTest() throws SQLException { String exp; @@ -186,13 +209,6 @@ private void queryScalar(String sql, Object val, Object res) throws SQLException @Test public void doubleBackslash() throws SQLException { Statement stmt = sharedConnection.createStatement(); - stmt.execute("DROP TABLE IF EXISTS TEST_SYNTAX_ERROR"); - stmt.execute( - "CREATE TABLE TEST_SYNTAX_ERROR(" - + " id INTEGER unsigned NOT NULL AUTO_INCREMENT, " - + " str_value MEDIUMTEXT CHARACTER SET utf8mb4 NOT NULL," - + " json_value MEDIUMTEXT CHARACTER SET utf8mb4 NOT NULL, " - + " PRIMARY KEY ( id ))"); stmt.execute( "INSERT INTO TEST_SYNTAX_ERROR(str_value, json_value) VALUES ('abc\\\\', '{\"data\": \"test\"}')"); } diff --git a/src/test/java/org/mariadb/jdbc/ScrollTypeTest.java b/src/test/java/org/mariadb/jdbc/ScrollTypeTest.java index 40b8d6d9a..c87904798 100644 --- a/src/test/java/org/mariadb/jdbc/ScrollTypeTest.java +++ b/src/test/java/org/mariadb/jdbc/ScrollTypeTest.java @@ -59,23 +59,32 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; public class ScrollTypeTest extends BaseTest { - /** - * Data initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("resultsSetReadingTest", "id int not null primary key auto_increment, test int"); - if (testSingleHost) { - Statement st = sharedConnection.createStatement(); - st.execute("INSERT INTO resultsSetReadingTest (test) values (1), (2), (3)"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE resultsSetReadingTest(id int not null primary key auto_increment, test int)"); + stmt.execute("CREATE TABLE scrollMultipleFetch(intvalue int)"); + stmt.execute("FLUSH TABLES"); + if (testSingleHost) { + stmt.execute("INSERT INTO resultsSetReadingTest (test) values (1), (2), (3)"); + } + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS resultsSetReadingTest"); + stmt.execute("DROP TABLE IF EXISTS scrollMultipleFetch"); } } @@ -139,8 +148,6 @@ public void scrollForwardOnlyStmt() throws SQLException { @Test public void scrollMultipleFetch() throws SQLException { - createTable("scrollMultipleFetch", "intvalue int"); - Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO scrollMultipleFetch values (1), (2), (3)"); stmt.setFetchSize(1); diff --git a/src/test/java/org/mariadb/jdbc/ServerPrepareStatementTest.java b/src/test/java/org/mariadb/jdbc/ServerPrepareStatementTest.java index 5dc95b81d..8bab6a37e 100644 --- a/src/test/java/org/mariadb/jdbc/ServerPrepareStatementTest.java +++ b/src/test/java/org/mariadb/jdbc/ServerPrepareStatementTest.java @@ -66,6 +66,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -73,48 +74,110 @@ public class ServerPrepareStatementTest extends BaseTest { - /** - * Tables initialisations. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "ServerPrepareStatementTest", "id int not null primary key auto_increment, test boolean"); - createTable( - "ServerPrepareStatementTestt", "id int not null primary key auto_increment, test boolean"); - createTable( - "ServerPrepareStatementTestt2", "id int not null primary key auto_increment, test boolean"); - createTable( - "ServerPrepareStatementTestCache", - "id int not null primary key auto_increment, test boolean"); - createTable( - "ServerPrepareStatementCacheSize3", - "id int not null primary key auto_increment, test boolean"); - if (doPrecisionTest) { - createTable( - "preparetestFactionnal", - "time0 TIME(6) default '22:11:00', timestamp0 timestamp(6), datetime0 datetime(6) "); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE ServerPrepareStatementTest(id int not null primary key auto_increment, test boolean)"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementTestt(id int not null primary key auto_increment, test boolean)"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementTestt2(id int not null primary key auto_increment, test boolean)"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementTestCache(id int not null primary key auto_increment, test boolean)"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementCacheSize3(id int not null primary key auto_increment, test boolean)"); + stmt.execute( + "CREATE TABLE preparetestFactionnal(time0 TIME(6) default '22:11:00', timestamp0 timestamp(6), datetime0 datetime(6))"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementCacheSize2(id int not null primary key auto_increment, test boolean)"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementCacheSize5(id int not null primary key auto_increment, test blob)"); + stmt.execute("CREATE TABLE ServerPrepareStatementParameters(id int, id2 int)"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementCacheSize4(id int not null primary key auto_increment, test LONGBLOB) ROW_FORMAT=COMPRESSED ENGINE=INNODB"); + stmt.execute("CREATE TABLE streamtest2(id int primary key not null, strm text)"); + stmt.execute( + "CREATE TABLE testServerPrepareMeta(id int not null primary key auto_increment, id2 int not null, id3 DEC(4,2), id4 BIGINT UNSIGNED)"); + stmt.execute( + "CREATE TABLE ServerPrepareStatementSync(id int not null primary key auto_increment, test varchar(1007), tt boolean)"); + + stmt.execute( + "CREATE TABLE preparetest(" + + "bit1 BIT(1)," + + "bit2 BIT(2)," + + "tinyint1 TINYINT(1)," + + "tinyint2 TINYINT(2)," + + "bool0 BOOL default 1," + + "smallint0 SMALLINT default 1," + + "smallint_unsigned SMALLINT UNSIGNED default 0," + + "mediumint0 MEDIUMINT default 1," + + "mediumint_unsigned MEDIUMINT UNSIGNED default 0," + + "int0 INT default 1," + + "int_unsigned INT UNSIGNED default 0," + + "bigint0 BIGINT default 1," + + "bigint_unsigned BIGINT UNSIGNED default 0," + + "float0 FLOAT default 0," + + "double0 DOUBLE default 1," + + "decimal0 DECIMAL default 0," + + "decimal1 DECIMAL(15,4) default 0," + + "date0 DATE default '2001-01-01'," + + "datetime0 DATETIME(6) default '2001-01-01 00:00:00'," + + "timestamp0 TIMESTAMP(6) default '2001-01-01 00:00:00'," + + "timestamp1 TIMESTAMP(0) null default '2001-01-01 00:00:00'," + + "timestamp_zero TIMESTAMP null, " + + "time0 TIME(6) default '22:11:00'," + + ((!isMariadbServer() && minVersion(5, 6)) + ? "year2 YEAR(4) default 99," + : "year2 YEAR(2) default 99,") + + "year4 YEAR(4) default 2011," + + "char0 CHAR(1) default '0'," + + "char_binary CHAR (1) binary default '0'," + + "varchar0 VARCHAR(1) default '1'," + + "varchar_binary VARCHAR(10) BINARY default 0x1," + + "binary0 BINARY(10) default 0x1," + + "varbinary0 VARBINARY(10) default 0x1, " + + "id int not null AUTO_INCREMENT, PRIMARY KEY (id))"); + stmt.execute( + "CREATE TABLE test_cache_table1(id1 int auto_increment primary key, text1 varchar(20), text2 varchar(20))"); + stmt.execute("CREATE TABLE PreparedStatementTest3(id int)"); + stmt.execute( + "CREATE TABLE ensureRowStateWithNullValues(t1 varchar(20), t2 varchar(20), t3 varchar(20), t4 varchar(20), t5 varchar(20), t6 varchar(20))"); + stmt.execute( + "CREATE TABLE ensureRowStateWithNullValuesSecond(ID int(11) NOT NULL," + + " COLUMN_1 varchar(11) COLLATE utf8_bin DEFAULT NULL," + + " COLUMN_2 varchar(11) COLLATE utf8_bin DEFAULT NULL," + + " COLUMN_3 varchar(11) COLLATE utf8_bin DEFAULT NULL," + + " PRIMARY KEY (ID))" + + "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"); + + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementTest"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementTestt"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementTestt2"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementTestCache"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementCacheSize3"); + stmt.execute("DROP TABLE IF EXISTS preparetestFactionnal"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementCacheSize2"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementCacheSize5"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementParameters"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementCacheSize4"); + stmt.execute("DROP TABLE IF EXISTS streamtest2"); + stmt.execute("DROP TABLE IF EXISTS testServerPrepareMeta"); + stmt.execute("DROP TABLE IF EXISTS ServerPrepareStatementSync"); + stmt.execute("DROP TABLE IF EXISTS preparetest"); + stmt.execute("DROP TABLE IF EXISTS test_cache_table1"); + stmt.execute("DROP TABLE IF EXISTS PreparedStatementTest3"); + stmt.execute("DROP TABLE IF EXISTS ensureRowStateWithNullValues"); + stmt.execute("DROP TABLE IF EXISTS ensureRowStateWithNullValuesSecond"); } - createTable( - "ServerPrepareStatementCacheSize2", - "id int not null primary key auto_increment, test boolean"); - createTable( - "ServerPrepareStatementCacheSize3", - "id int not null primary key auto_increment, test blob"); - createTable("ServerPrepareStatementParameters", "id int, id2 int"); - createTable( - "ServerPrepareStatementCacheSize4", - "id int not null primary key auto_increment, test LONGBLOB", - "ROW_FORMAT=COMPRESSED ENGINE=INNODB"); - createTable("streamtest2", "id int primary key not null, strm text"); - createTable( - "testServerPrepareMeta", - "id int not null primary key auto_increment, id2 int not null, id3 DEC(4,2), id4 BIGINT UNSIGNED "); - createTable( - "ServerPrepareStatementSync", - "id int not null primary key auto_increment, test varchar(1007), tt boolean"); } @Test @@ -356,53 +419,12 @@ public void timeFractionnalSecondTest() throws SQLException { } } - private void prepareTestTable() throws SQLException { - - createTable( - "preparetest", - "bit1 BIT(1)," - + "bit2 BIT(2)," - + "tinyint1 TINYINT(1)," - + "tinyint2 TINYINT(2)," - + "bool0 BOOL default 1," - + "smallint0 SMALLINT default 1," - + "smallint_unsigned SMALLINT UNSIGNED default 0," - + "mediumint0 MEDIUMINT default 1," - + "mediumint_unsigned MEDIUMINT UNSIGNED default 0," - + "int0 INT default 1," - + "int_unsigned INT UNSIGNED default 0," - + "bigint0 BIGINT default 1," - + "bigint_unsigned BIGINT UNSIGNED default 0," - + "float0 FLOAT default 0," - + "double0 DOUBLE default 1," - + "decimal0 DECIMAL default 0," - + "decimal1 DECIMAL(15,4) default 0," - + "date0 DATE default '2001-01-01'," - + "datetime0 DATETIME(6) default '2001-01-01 00:00:00'," - + "timestamp0 TIMESTAMP(6) default '2001-01-01 00:00:00'," - + "timestamp1 TIMESTAMP(0) null default '2001-01-01 00:00:00'," - + "timestamp_zero TIMESTAMP null, " - + "time0 TIME(6) default '22:11:00'," - + ((!isMariadbServer() && minVersion(5, 6)) - ? "year2 YEAR(4) default 99," - : "year2 YEAR(2) default 99,") - + "year4 YEAR(4) default 2011," - + "char0 CHAR(1) default '0'," - + "char_binary CHAR (1) binary default '0'," - + "varchar0 VARCHAR(1) default '1'," - + "varchar_binary VARCHAR(10) BINARY default 0x1," - + "binary0 BINARY(10) default 0x1," - + "varbinary0 VARBINARY(10) default 0x1, " - + "id int not null AUTO_INCREMENT, PRIMARY KEY (id)"); - } - @SuppressWarnings("ConstantConditions") @Test public void dataConformity() throws SQLException { Assume.assumeTrue(doPrecisionTest); TimeZone defaultTimeZone = TimeZone.getDefault(); try { - prepareTestTable(); PreparedStatement ps = sharedConnection.prepareStatement( "INSERT INTO preparetest (bit1,bit2,tinyint1," @@ -656,7 +678,7 @@ public void blobTest() throws Throwable { try (Connection connection = setConnection("&prepStmtCacheSize=10")) { PreparedStatement ps = connection.prepareStatement( - "INSERT INTO ServerPrepareStatementCacheSize3(test) VALUES (?)"); + "INSERT INTO ServerPrepareStatementCacheSize5(test) VALUES (?)"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("logback-test.xml"); @@ -751,7 +773,7 @@ public void readerTest() throws Throwable { try (Connection connection = setConnection("&prepStmtCacheSize=10")) { PreparedStatement ps = connection.prepareStatement( - "INSERT INTO ServerPrepareStatementCacheSize3(test) VALUES (?)"); + "INSERT INTO ServerPrepareStatementCacheSize5(test) VALUES (?)"); Reader reader = new BufferedReader( new InputStreamReader(ClassLoader.getSystemResourceAsStream("logback-test.xml"))); @@ -876,8 +898,7 @@ public void directExecuteNumber() throws Throwable { @Test public void dataConformity2() throws SQLException { Assume.assumeTrue(doPrecisionTest); - prepareTestTable(); - + sharedConnection.createStatement().execute("TRUNCATE preparetest"); PreparedStatement ps = sharedConnection.prepareStatement( "INSERT INTO preparetest " @@ -1008,9 +1029,6 @@ public void testPrepareStatementCache() throws Throwable { // tester le cache prepareStatement try (Connection connection = setConnection()) { Protocol protocol = getProtocolFromConnection(connection); - createTable( - "test_cache_table1", - "id1 int auto_increment primary key, text1 varchar(20), text2 varchar(20)"); PreparedStatement[] map = new PreparedStatement[280]; for (int i = 0; i < 280; i++) { map[i] = @@ -1037,7 +1055,6 @@ public void testPrepareStatementCache() throws Throwable { */ @Test public void testRewriteMultiPacket() throws SQLException { - createTable("PreparedStatementTest3", "id int"); StringBuilder sql = new StringBuilder("INSERT INTO PreparedStatementTest3 VALUES (?)"); for (int i = 1; i < 65535; i++) { sql.append(",(?)"); @@ -1129,9 +1146,6 @@ public void serverPrepareStatementSync() throws Throwable { */ @Test public void ensureRowStateWithNullValues() throws SQLException { - createTable( - "ensureRowStateWithNullValues", - "t1 varchar(20), t2 varchar(20), t3 varchar(20), t4 varchar(20), t5 varchar(20), t6 varchar(20)"); Statement stmt = sharedConnection.createStatement(); stmt.execute( "INSERT INTO ensureRowStateWithNullValues VALUES ('12345678901234567890', null, 'otherString', '1234567890', null, '12345')"); @@ -1156,14 +1170,6 @@ public void ensureRowStateWithNullValues() throws SQLException { */ @Test public void ensureRowStateWithNullValuesSecond() throws Exception { - createTable( - "ensureRowStateWithNullValuesSecond", - " ID int(11) NOT NULL," - + " COLUMN_1 varchar(11) COLLATE utf8_bin DEFAULT NULL," - + " COLUMN_2 varchar(11) COLLATE utf8_bin DEFAULT NULL," - + " COLUMN_3 varchar(11) COLLATE utf8_bin DEFAULT NULL," - + " PRIMARY KEY (ID)", - "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"); if (testSingleHost) { Statement st = sharedConnection.createStatement(); st.execute( diff --git a/src/test/java/org/mariadb/jdbc/SslTest.java b/src/test/java/org/mariadb/jdbc/SslTest.java index 4cb951759..73969a670 100644 --- a/src/test/java/org/mariadb/jdbc/SslTest.java +++ b/src/test/java/org/mariadb/jdbc/SslTest.java @@ -87,7 +87,9 @@ public class SslTest extends BaseTest { /** Enable Crypto. */ @BeforeClass public static void enableCrypto() { - Assume.assumeFalse(System.getenv("SKYSQL") != null || "true".equals(System.getenv("AURORA"))); + Assume.assumeFalse( + System.getenv("SKYSQL") != null && System.getenv("SKYSQL_HA") == null + || "true".equals(System.getenv("AURORA"))); try { Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted"); field.setAccessible(true); @@ -119,7 +121,9 @@ public void checkSsl() throws SQLException { throw new SQLException("unexpected exception :" + ioe.getMessage()); } - if (System.getProperty("serverCertificatePath") == null && System.getenv("SKYSQL") == null) { + if (System.getProperty("serverCertificatePath") == null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null) { try (ResultSet rs = sharedConnection.createStatement().executeQuery("select @@ssl_cert")) { assertTrue(rs.next()); serverCertificatePath = rs.getString(1); @@ -453,7 +457,7 @@ public void testConnect(Properties info, boolean sslExpected) throws SQLExceptio */ public void testConnect(Properties info, boolean sslExpected, String user, String pwd) throws SQLException { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(haveSsl(sharedConnection) && isMariadbServer()); try (Connection conn = createConnection(info, user, pwd, sslPort)) { diff --git a/src/test/java/org/mariadb/jdbc/StateChangeTest.java b/src/test/java/org/mariadb/jdbc/StateChangeTest.java index 112fdde36..d1b534e0b 100644 --- a/src/test/java/org/mariadb/jdbc/StateChangeTest.java +++ b/src/test/java/org/mariadb/jdbc/StateChangeTest.java @@ -55,11 +55,30 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; public class StateChangeTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE autoIncrementChange(id int not null primary key auto_increment, name char(20))"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS autoIncrementChange"); + } + } + @Test public void databaseStateChange() throws SQLException { Assume.assumeTrue( @@ -106,7 +125,6 @@ public void autoIncrementChange() throws SQLException { Assume.assumeFalse(isGalera()); Assume.assumeTrue( (isMariadbServer() && minVersion(10, 2)) || (!isMariadbServer() && minVersion(5, 7))); - createTable("autoIncrementChange", "id int not null primary key auto_increment, name char(20)"); try (Connection connection = setConnection()) { try (Statement stmt = connection.createStatement()) { try (PreparedStatement preparedStatement = diff --git a/src/test/java/org/mariadb/jdbc/StatementTest.java b/src/test/java/org/mariadb/jdbc/StatementTest.java index 23202c1ad..541946e25 100644 --- a/src/test/java/org/mariadb/jdbc/StatementTest.java +++ b/src/test/java/org/mariadb/jdbc/StatementTest.java @@ -58,6 +58,7 @@ import java.nio.charset.StandardCharsets; import java.sql.*; import java.util.Properties; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; @@ -82,17 +83,51 @@ public class StatementTest extends BaseTest { private static final String ER_LOAD_DATA_INVALID_COLUMN_STATE = "HY000"; private static final String ER_ADD_PARTITION_NO_NEW_PARTITION_STATE = "HY000"; - /** - * Initializing tables. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("vendor_code_test", "id int not null primary key auto_increment, test boolean"); - createTable("vendor_code_test2", "a INT", "PARTITION BY KEY (a) (PARTITION x0, PARTITION x1)"); - createTable("vendor_code_test3", "a INT", "PARTITION BY LIST(a) (PARTITION p0 VALUES IN (1))"); - createTable("StatementTestt1", "c1 INT, c2 VARCHAR(255)"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE vendor_code_test(id int not null primary key auto_increment, test boolean)"); + stmt.execute( + "CREATE TABLE vendor_code_test2(a INT) PARTITION BY KEY (a) (PARTITION x0, PARTITION x1)"); + stmt.execute( + "CREATE TABLE vendor_code_test3(a INT) PARTITION BY LIST(a) (PARTITION p0 VALUES IN (1))"); + stmt.execute("CREATE TABLE StatementTestt1(c1 INT, c2 VARCHAR(255))"); + stmt.execute("CREATE TABLE testFractionalTimeBatch(tt TIMESTAMP(6))"); + stmt.execute("CREATE TABLE testFallbackBatchUpdate(col int)"); + stmt.execute("CREATE TABLE testProperBatchUpdate(col int, col2 int)"); + stmt.execute("CREATE TABLE deadlock(a int primary key)"); + stmt.execute( + "CREATE TABLE largeUpdate(a int not null primary key auto_increment, t varchar(256))"); + stmt.execute( + "CREATE TABLE largePrepareUpdate(a int not null primary key auto_increment, t varchar(256))"); + stmt.execute( + "CREATE PROCEDURE ensureStreamingState(INOUT p1 INT) BEGIN SELECT * from seq_1_to_3; SELECT * from seq_5_to_7; END"); + stmt.execute( + "create view vendor_code_test_view as select id as id1, id as id2, test " + + "from vendor_code_test"); + + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP view IF EXISTS vendor_code_test_view"); + stmt.execute("DROP TABLE IF EXISTS vendor_code_test"); + stmt.execute("DROP TABLE IF EXISTS vendor_code_test2"); + stmt.execute("DROP TABLE IF EXISTS vendor_code_test3"); + stmt.execute("DROP TABLE IF EXISTS StatementTestt1"); + stmt.execute("DROP TABLE IF EXISTS testFractionalTimeBatch"); + stmt.execute("DROP TABLE IF EXISTS testFallbackBatchUpdate"); + stmt.execute("DROP TABLE IF EXISTS testProperBatchUpdate"); + stmt.execute("DROP TABLE IF EXISTS deadlock"); + stmt.execute("DROP TABLE IF EXISTS largeUpdate"); + stmt.execute("DROP TABLE IF EXISTS largePrepareUpdate"); + stmt.execute("DROP PROCEDURE IF EXISTS ensureStreamingState"); + } } @Test @@ -158,10 +193,6 @@ public void testColumnsDoNotExist() { @Test public void testNonInsertableTable() throws SQLException { Statement statement = sharedConnection.createStatement(); - statement.execute( - "create or replace view vendor_code_test_view as select id as id1, id as id2, test " - + "from vendor_code_test"); - try { statement.executeQuery("insert into vendor_code_test_view VALUES (null, null, true)"); fail("The above statement should result in an exception"); @@ -278,7 +309,7 @@ public void testLoadDataInvalidColumn() throws SQLException { throw new SQLException("Mariadb JDBC adaptor must be used"); } try { - String data = "\"1\", \"string1\"\n" + "\"2\", \"string2\"\n" + "\"3\", \"string3\"\n"; + String data = "\"1\", \"string1\"\n\"2\", \"string2\"\n\"3\", \"string3\"\n"; ByteArrayInputStream loadDataInfileFile = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); mysqlStatement.setLocalInfileInputStream(loadDataInfileFile); @@ -355,8 +386,6 @@ public void closeOnCompletion() throws SQLException { @Test public void testFractionalTimeBatch() throws SQLException { Assume.assumeTrue(doPrecisionTest); - - createTable("testFractionalTimeBatch", "tt TIMESTAMP(6)"); Timestamp currTime = new Timestamp(System.currentTimeMillis()); try (PreparedStatement preparedStatement = sharedConnection.prepareStatement("INSERT INTO testFractionalTimeBatch (tt) values (?)")) { @@ -378,8 +407,6 @@ public void testFractionalTimeBatch() throws SQLException { @Test public void testFallbackBatchUpdate() throws SQLException { Assume.assumeTrue(doPrecisionTest); - - createTable("testFallbackBatchUpdate", "col int"); Statement statement = sharedConnection.createStatement(); // add 100 data @@ -417,8 +444,6 @@ public void testFallbackBatchUpdate() throws SQLException { @Test public void testProperBatchUpdate() throws SQLException { Assume.assumeTrue(doPrecisionTest); - - createTable("testProperBatchUpdate", "col int, col2 int"); Statement statement = sharedConnection.createStatement(); // add 100 data @@ -457,7 +482,6 @@ public void testProperBatchUpdate() throws SQLException { @Test public void deadLockInformation() throws SQLException { - createTable("deadlock", "a int primary key", "engine=innodb"); Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into deadlock(a) values(0), (1)"); @@ -500,10 +524,6 @@ public void deadLockInformation() throws SQLException { @Test public void largeUpdate() throws SQLException { - createTable( - "largeUpdate", - "a int not null primary key auto_increment, t varchar(256)", - "engine=innodb"); Statement stmt = sharedConnection.createStatement(); long updateRes = stmt.executeLargeUpdate("insert into largeUpdate(t) values('a'), ('b')"); @@ -574,10 +594,6 @@ public void closedStatement() throws SQLException { @Test public void largePrepareUpdate() throws SQLException { - createTable( - "largePrepareUpdate", - "a int not null primary key auto_increment, t varchar(256)", - "engine=innodb"); Statement stmt = sharedConnection.createStatement(); stmt.addBatch("insert into largePrepareUpdate(t) values('a')"); stmt.addBatch("insert into largePrepareUpdate(t) values('b')"); @@ -747,9 +763,6 @@ public void escaping() throws Exception { @Test public void ensureStreamingState() throws Exception { Assume.assumeTrue(isMariadbServer() && minVersion(10, 1)); - createProcedure( - "ensureStreamingState", - "(INOUT p1 INT) BEGIN SELECT * from seq_1_to_3; SELECT * from " + "seq_5_to_7; END"); Statement stmt = sharedConnection.createStatement(); PreparedStatement prep = sharedConnection.prepareCall("CALL ensureStreamingState(?)"); prep.setObject(1, 5); diff --git a/src/test/java/org/mariadb/jdbc/StoredProcedureTest.java b/src/test/java/org/mariadb/jdbc/StoredProcedureTest.java index f3e7a9f3d..7fa5c0293 100644 --- a/src/test/java/org/mariadb/jdbc/StoredProcedureTest.java +++ b/src/test/java/org/mariadb/jdbc/StoredProcedureTest.java @@ -61,42 +61,229 @@ import java.lang.reflect.Method; import java.sql.*; import java.util.Properties; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; public class StoredProcedureTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createProcedure("useParameterName", "(a int) begin select a; end"); - createProcedure("useWrongParameterName", "(a int) begin select a; end"); - createProcedure("multiResultSets", "() BEGIN SELECT 1; SELECT 2; END"); - createProcedure("inoutParam", "(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); - createProcedure("testGetProcedures", "(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); - createProcedure("withStrangeParameter", "(IN a DECIMAL(10,2)) begin select a; end"); - createProcedure( - "TEST_SP1", - "() BEGIN\n" - + "SELECT @Something := 'Something';\n" - + "SIGNAL SQLSTATE '70100'\n" - + "SET MESSAGE_TEXT = 'Test error from SP'; \n" - + "END"); - - // sequence table are not in MySQL and MariaDB < 10.1, so create some basic table - createTable("table_10", "val int"); - createTable("table_5", "val int"); - if (testSingleHost) { - try (Statement stmt = sharedConnection.createStatement()) { - stmt.execute("INSERT INTO table_10 VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)"); - stmt.execute("INSERT INTO table_5 VALUES (1),(2),(3),(4),(5)"); - } + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS testProcMultiDb"); + stmt.execute("CREATE PROCEDURE useParameterName(a int) begin select a; end"); + stmt.execute("CREATE PROCEDURE useWrongParameterName(a int) begin select a; end"); + stmt.execute("CREATE PROCEDURE multiResultSets() BEGIN SELECT 1; SELECT 2; END"); + stmt.execute("CREATE PROCEDURE inoutParam(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); + stmt.execute("CREATE PROCEDURE testGetProcedures(INOUT p1 INT) begin set p1 = p1 + 1; end\n"); + stmt.execute("CREATE PROCEDURE withStrangeParameter(IN a DECIMAL(10,2)) begin select a; end"); + stmt.execute( + "CREATE PROCEDURE TEST_SP1() BEGIN\n" + + "SELECT @Something := 'Something';\n" + + "SIGNAL SQLSTATE '70100'\n" + + "SET MESSAGE_TEXT = 'Test error from SP'; \n" + + "END"); + stmt.execute( + "CREATE PROCEDURE StoredWithOutput(out MAX_PARAM TINYINT, out MIN_PARAM TINYINT, out NULL_PARAM TINYINT)" + + "begin select 1,0,null into MAX_PARAM, MIN_PARAM, NULL_PARAM from dual; SELECT * from table_10; SELECT * from table_5;end"); + stmt.execute( + "CREATE PROCEDURE StreamInterrupted(out MAX_PARAM TINYINT, out MIN_PARAM TINYINT, out NULL_PARAM TINYINT)" + + "begin select 1,0,null into MAX_PARAM, MIN_PARAM, NULL_PARAM from dual; SELECT * from table_10; SELECT * from table_5;end"); + stmt.execute( + "CREATE PROCEDURE StreamWithoutOutput(IN MAX_PARAM TINYINT)begin SELECT * from table_10; SELECT * from table_5;end"); + stmt.execute( + "CREATE PROCEDURE testProcDecimalComa(decimalParam DECIMAL(18,0))\nBEGIN\n SELECT 1;\nEND"); + stmt.execute( + "CREATE PROCEDURE prepareStmtWithOutParameter(x int, INOUT y int)\nBEGIN\nSELECT 1;end\n"); + stmt.execute("CREATE PROCEDURE withResultSet(a int) begin select a; end"); + stmt.execute("CREATE PROCEDURE callabletest1()\nBEGIN\nSELECT 1;end\n"); + stmt.execute( + "CREATE PROCEDURE testMetaCatalog(x int, out y int) COMMENT 'my comment' \nBEGIN\nSET y = 2;\n end\n"); + stmt.execute( + "CREATE PROCEDURE testInOutParam(IN p1 VARCHAR(255), INOUT p2 INT)\n" + + "begin\n" + + " DECLARE z INT;\n" + + " SET z = p2 + 1;\n" + + " SET p2 = z;\n" + + " SELECT p1;\n" + + " SELECT CONCAT('todo ', p1);\n" + + "end"); + stmt.execute( + "CREATE PROCEDURE testResultsetWithInoutParameter(INOUT testValue VARCHAR(10))\n" + + "BEGIN\n" + + " insert into testResultsetWithInoutParameterTb(test) values (testValue);\n" + + " SELECT testValue;\n" + + " SET testValue = UPPER(testValue);\n" + + "END"); + stmt.execute( + "CREATE PROCEDURE simpleproc(IN inParam CHAR(20), INOUT inOutParam CHAR(20), OUT outParam CHAR(50))" + + " BEGIN\n" + + " SET inOutParam = UPPER(inOutParam);\n" + + " SET outParam = CONCAT('Hello, ', inOutParam, ' and ', inParam);" + + " SELECT 'a' FROM DUAL;\n" + + " END;"); + stmt.execute("CREATE PROCEDURE testProcedureParenthesis() BEGIN SELECT 1; END"); + stmt.execute("CREATE PROCEDURE testProcLinefeed(\r\n)\r\n BEGIN SELECT 1; END"); + stmt.execute( + "CREATE PROCEDURE testStreamInOutWithName(INOUT mblob MEDIUMBLOB) BEGIN SELECT 1 FROM DUAL WHERE 1=0;\nEND"); + stmt.execute( + "CREATE PROCEDURE testProcedureComment(a INT, b VARCHAR(32)) BEGIN SELECT CONCAT(CONVERT(a, CHAR(50)), b); END"); + stmt.execute( + "CREATE PROCEDURE testCallableNullSettersProc" + + "(OUT value_1_v BIGINT, IN value_2_v BIGINT, IN value_3_v VARCHAR(20)) " + + "BEGIN " + + "INSERT INTO testCallableNullSettersTable VALUES (value_2_v,value_3_v); " + + "SET value_1_v = value_2_v; " + + "END;"); + + stmt.execute( + "CREATE FUNCTION testFunctionCall(a float, b bigint, c int) RETURNS INT NO SQL\nBEGIN\nRETURN a;\nEND"); + stmt.execute( + "CREATE FUNCTION callFunctionWithNoParameters()\n RETURNS CHAR(50) DETERMINISTIC\n RETURN 'mike';"); + stmt.execute( + "CREATE FUNCTION testFunctionWith2parameters(s CHAR(20), s2 CHAR(20))\n" + + " RETURNS CHAR(50) DETERMINISTIC\n" + + " RETURN CONCAT(s,' and ', s2)"); + stmt.execute("CREATE FUNCTION testFunctionParenthesis() RETURNS INT DETERMINISTIC RETURN 1;"); + stmt.execute( + "CREATE FUNCTION testCallableNullSetters(value_1_v BIGINT, value_2_v VARCHAR(20)) RETURNS BIGINT " + + "DETERMINISTIC MODIFIES SQL DATA BEGIN " + + "INSERT INTO testCallableNullSettersTable VALUES (value_1_v,value_2_v); " + + "RETURN value_1_v; " + + "END;"); + stmt.execute( + "CREATE FUNCTION test_function() RETURNS BIGINT DETERMINISTIC MODIFIES SQL DATA BEGIN DECLARE max_value BIGINT; " + + "SELECT MAX(value_1) INTO max_value FROM testCallableThrowException2; RETURN max_value; END;"); + stmt.execute("CREATE TABLE testCallableThrowException3(value_1 BIGINT PRIMARY KEY)"); + stmt.execute( + "CREATE TABLE testCallableThrowException4(value_2 BIGINT PRIMARY KEY, " + + " FOREIGN KEY (value_2) REFERENCES testCallableThrowException3 (value_1) ON DELETE CASCADE)"); + + stmt.execute( + "CREATE FUNCTION test_function2(value BIGINT) RETURNS BIGINT DETERMINISTIC MODIFIES SQL DATA BEGIN " + + "INSERT INTO testCallableThrowException4 VALUES (value); RETURN value; END;"); + + stmt.execute( + "CREATE FUNCTION testFunctionWithFixedParameter(a varchar(40), b bigint(20), c varchar(80)) RETURNS bigint(20) LANGUAGE SQL DETERMINISTIC " + + "MODIFIES SQL DATA COMMENT 'bbb' BEGIN RETURN 1; END; "); + + stmt.execute( + "CREATE TABLE TMIX91P(" + + "F01SMALLINT SMALLINT NOT NULL, F02INTEGER INTEGER,F03REAL REAL," + + "F04FLOAT FLOAT,F05NUMERIC31X4 NUMERIC(31,4), F06NUMERIC16X16 NUMERIC(16,16), F07CHAR_10 CHAR(10)," + + " F08VARCHAR_10 VARCHAR(10), F09CHAR_20 CHAR(20), F10VARCHAR_20 VARCHAR(20), F11DATE DATE," + + " F12DATETIME DATETIME, PRIMARY KEY (F01SMALLINT))"); + + stmt.execute( + "CREATE PROCEDURE MSQSPR100\n( p1_in INTEGER , p2_in CHAR(20), OUT p3_out INTEGER, OUT p4_out CHAR(11))\nBEGIN " + + "\n SELECT F01SMALLINT,F02INTEGER, F11DATE,F12DATETIME,F03REAL \n FROM TMIX91P WHERE F02INTEGER = p1_in; " + + "\n SELECT F02INTEGER,F07CHAR_10,F08VARCHAR_10,F09CHAR_20 \n FROM TMIX91P WHERE F09CHAR_20 = p2_in ORDER BY F02INTEGER ; " + + "\n SET p3_out = 144; \n SET p4_out = 'CHARACTER11'; \n SELECT p3_out, p4_out; END"); + stmt.execute( + "CREATE PROCEDURE testParameterNumber_1(OUT nfact VARCHAR(100), IN ccuenta VARCHAR(100),\nOUT ffact VARCHAR(100),\nOUT fdoc VARCHAR(100))\nBEGIN" + + "\nSET nfact = 'ncfact string';\nSET ffact = 'ffact string';\nSET fdoc = 'fdoc string';\nEND"); + stmt.execute( + "CREATE PROCEDURE testParameterNumber_2(IN ccuent1 VARCHAR(100), IN ccuent2 VARCHAR(100),\nOUT nfact VARCHAR(100),\nOUT ffact VARCHAR(100)," + + "\nOUT fdoc VARCHAR(100))\nBEGIN\nSET nfact = 'ncfact string';\nSET ffact = 'ffact string';\n" + + "SET fdoc = 'fdoc string';\nEND"); + stmt.execute( + "CREATE PROCEDURE testProcMultiDb.testProcMultiDbProc(x int, out y int)\nbegin\ndeclare z int;\nset z = x+1, y = z;\nend\n"); + stmt.execute( + "CREATE PROCEDURE testProcSendNullInOut_1(INOUT x INTEGER)\nBEGIN\nSET x = x + 1;\nEND"); + stmt.execute( + "CREATE PROCEDURE testProcSendNullInOut_2(x INTEGER, OUT y INTEGER)\nBEGIN\nSET y = x + 1;\nEND"); + stmt.execute( + "CREATE PROCEDURE testProcSendNullInOut_3(INOUT x INTEGER)\nBEGIN\nSET x = 10;\nEND"); + stmt.execute( + "CREATE FUNCTION hello()\n RETURNS CHAR(50) DETERMINISTIC\n RETURN CONCAT('Hello, !');"); + stmt.execute( + "CREATE PROCEDURE issue425(IN inValue TEXT, OUT testValue TEXT)\n" + + "BEGIN\n" + + " set testValue = CONCAT('o', inValue);\n" + + "END"); + stmt.execute( + "CREATE FUNCTION issue425f(a TEXT, b TEXT) RETURNS TEXT NO SQL\nBEGIN\nRETURN CONCAT(a, b);\nEND"); + stmt.execute("CREATE PROCEDURE cacheCall(IN inValue int)\nBEGIN\n /*do nothing*/ \nEND"); + stmt.execute( + "CREATE FUNCTION hello2()\n RETURNS CHAR(50) DETERMINISTIC\n RETURN CONCAT('Hello, !');"); + stmt.execute( + "CREATE PROCEDURE CONJ791(IN a TEXT, OUT b DATETIME) \nBEGIN\nSET b := '2006-01-01 01:01:16';\nEND"); + + stmt.execute("CREATE TABLE testResultsetWithInoutParameterTb(test VARCHAR(10))"); + stmt.execute("CREATE TABLE table_10(val int)"); + stmt.execute("CREATE TABLE table_5(val int)"); + stmt.execute("CREATE TABLE testCallableThrowException1(value_1 BIGINT PRIMARY KEY)"); + stmt.execute("CREATE TABLE testCallableThrowException2(value_2 BIGINT PRIMARY KEY)"); + stmt.execute( + "CREATE TABLE testCallableNullSettersTable(value_1 BIGINT PRIMARY KEY,value_2 VARCHAR(20))"); + + stmt.execute("INSERT INTO table_10 VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)"); + stmt.execute("INSERT INTO table_5 VALUES (1),(2),(3),(4),(5)"); + + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP DATABASE IF EXISTS testProcMultiDb"); + stmt.execute("DROP PROCEDURE IF EXISTS useParameterName"); + stmt.execute("DROP PROCEDURE IF EXISTS useWrongParameterName"); + stmt.execute("DROP PROCEDURE IF EXISTS multiResultSets"); + stmt.execute("DROP PROCEDURE IF EXISTS inoutParam"); + stmt.execute("DROP PROCEDURE IF EXISTS testGetProcedures"); + stmt.execute("DROP PROCEDURE IF EXISTS withStrangeParameter"); + stmt.execute("DROP PROCEDURE IF EXISTS TEST_SP1"); + stmt.execute("DROP PROCEDURE IF EXISTS StoredWithOutput"); + stmt.execute("DROP PROCEDURE IF EXISTS StreamInterrupted"); + stmt.execute("DROP PROCEDURE IF EXISTS StreamWithoutOutput"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcDecimalComa"); + stmt.execute("DROP PROCEDURE IF EXISTS prepareStmtWithOutParameter"); + stmt.execute("DROP PROCEDURE IF EXISTS withResultSet"); + stmt.execute("DROP PROCEDURE IF EXISTS callabletest1"); + stmt.execute("DROP PROCEDURE IF EXISTS testMetaCatalog"); + stmt.execute("DROP PROCEDURE IF EXISTS testInOutParam"); + stmt.execute("DROP PROCEDURE IF EXISTS testResultsetWithInoutParameter"); + stmt.execute("DROP PROCEDURE IF EXISTS simpleproc"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcedureParenthesis"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcLinefeed"); + stmt.execute("DROP PROCEDURE IF EXISTS testStreamInOutWithName"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcedureComment"); + stmt.execute("DROP PROCEDURE IF EXISTS testCallableNullSettersProc"); + + stmt.execute("DROP FUNCTION IF EXISTS testFunctionCall"); + stmt.execute("DROP FUNCTION IF EXISTS callFunctionWithNoParameters"); + stmt.execute("DROP FUNCTION IF EXISTS testFunctionWith2parameters"); + stmt.execute("DROP FUNCTION IF EXISTS testFunctionParenthesis"); + stmt.execute("DROP FUNCTION IF EXISTS testCallableNullSetters"); + stmt.execute("DROP FUNCTION IF EXISTS test_function"); + stmt.execute("DROP FUNCTION IF EXISTS test_function2"); + stmt.execute("DROP FUNCTION IF EXISTS testFunctionWithFixedParameter"); + + stmt.execute("DROP TABLE IF EXISTS TMIX91P"); + + stmt.execute("DROP PROCEDURE IF EXISTS MSQSPR100"); + stmt.execute("DROP PROCEDURE IF EXISTS testParameterNumber_1"); + stmt.execute("DROP PROCEDURE IF EXISTS testParameterNumber_2"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcMultiDb.testProcMultiDbProc"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcSendNullInOut_1"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcSendNullInOut_2"); + stmt.execute("DROP PROCEDURE IF EXISTS testProcSendNullInOut_3"); + stmt.execute("DROP FUNCTION IF EXISTS hello"); + stmt.execute("DROP PROCEDURE IF EXISTS issue425"); + stmt.execute("DROP FUNCTION IF EXISTS issue425f"); + stmt.execute("DROP PROCEDURE IF EXISTS cacheCall"); + stmt.execute("DROP FUNCTION IF EXISTS hello2"); + stmt.execute("DROP PROCEDURE IF EXISTS CONJ791"); + + stmt.execute("DROP TABLE IF EXISTS testResultsetWithInoutParameterTb"); + stmt.execute("DROP TABLE IF EXISTS table_10"); + stmt.execute("DROP TABLE IF EXISTS table_5"); + stmt.execute("DROP TABLE IF EXISTS testCallableThrowException1"); + stmt.execute("DROP TABLE IF EXISTS testCallableThrowException2"); + stmt.execute("DROP TABLE IF EXISTS testCallableNullSettersTable"); + stmt.execute("DROP TABLE IF EXISTS testCallableThrowException4"); + stmt.execute("DROP TABLE IF EXISTS testCallableThrowException3"); } } @@ -111,11 +298,6 @@ public void testStoreProcedureStreaming() throws Exception { cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - createProcedure( - "StoredWithOutput", - "(out MAX_PARAM TINYINT, out MIN_PARAM TINYINT, out NULL_PARAM TINYINT)" - + "begin select 1,0,null into MAX_PARAM, MIN_PARAM, NULL_PARAM from dual; SELECT * from table_10; SELECT * from table_5;end"); - try (CallableStatement callableStatement = sharedConnection.prepareCall("{call StoredWithOutput(?,?,?)}")) { // indicate to stream results @@ -160,11 +342,6 @@ public void testStoreProcedureStreamingWithAnotherQuery() throws Exception { cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - createProcedure( - "StreamInterrupted", - "(out MAX_PARAM TINYINT, out MIN_PARAM TINYINT, out NULL_PARAM TINYINT)" - + "begin select 1,0,null into MAX_PARAM, MIN_PARAM, NULL_PARAM from dual; SELECT * from table_10; SELECT * from table_5;end"); - try (CallableStatement callableStatement = sharedConnection.prepareCall("{call StreamInterrupted(?,?,?)}")) { // indicate to stream results @@ -212,10 +389,6 @@ public void testStoreProcedureStreamingWithAnotherQuery() throws Exception { @Test public void testStoreProcedureStreamingWithoutOutput() throws Exception { - createProcedure( - "StreamWithoutOutput", - "(IN MAX_PARAM TINYINT)" + "begin SELECT * from table_10; SELECT * from table_5;end"); - try (CallableStatement callableStatement = sharedConnection.prepareCall("{call StreamWithoutOutput(?)}")) { // indicate to stream results @@ -294,9 +467,6 @@ public void callWithOutParameter() throws SQLException { cancelForVersion(10, 2, 2); cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - - createProcedure( - "prepareStmtWithOutParameter", "(x int, INOUT y int)\n" + "BEGIN\n" + "SELECT 1;end\n"); CallableStatement callableStatement = sharedConnection.prepareCall("{call prepareStmtWithOutParameter(?,?)}"); callableStatement.registerOutParameter(2, Types.INTEGER); @@ -308,7 +478,6 @@ public void callWithOutParameter() throws SQLException { @Test public void callWithResultSet() throws Exception { - createProcedure("withResultSet", "(a int) begin select a; end"); CallableStatement stmt = sharedConnection.prepareCall("{call withResultSet(?)}"); stmt.setInt(1, 1); ResultSet rs = stmt.executeQuery(); @@ -393,7 +562,6 @@ public void callWithStrangeParameter() throws SQLException { @Test public void meta() throws Exception { - createProcedure("callabletest1", "()\nBEGIN\nSELECT 1;end\n"); ResultSet rs = sharedConnection.getMetaData().getProcedures(null, null, "callabletest1"); if (rs.next()) { assertTrue("callabletest1".equals(rs.getString(3))); @@ -404,7 +572,7 @@ public void meta() throws Exception { @Test public void testMetaCatalogNoAccessToProcedureBodies() throws Exception { - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); // cancel for version 10.2 beta before fix https://jira.mariadb.org/browse/MDEV-11761 cancelForVersion(10, 2, 2); @@ -429,9 +597,6 @@ public void testMetaCatalogNoAccessToProcedureBodies() throws Exception { properties.put("user", "test_jdbc"); properties.put("password", "testJ@dc1"); - createProcedure( - "testMetaCatalog", "(x int, out y int) COMMENT 'my comment' \nBEGIN\nSET y = 2;\n end\n"); - try (Connection connection = openConnection(connU, properties)) { CallableStatement callableStatement = connection.prepareCall("{call testMetaCatalog(?, ?)}"); callableStatement.registerOutParameter(2, Types.INTEGER); @@ -480,49 +645,45 @@ public void testMetaCatalogNoAccessToProcedureBodies() throws Exception { @Test public void testSameProcedureWithDifferentParameters() throws Exception { - sharedConnection.createStatement().executeUpdate("CREATE DATABASE IF NOT EXISTS testj2"); - - createProcedure( - "testj.testSameProcedureWithDifferentParameters", - "(OUT p1 VARCHAR(10), IN p2 VARCHAR(10))\nBEGIN" + "\nselect 1;" + "\nEND"); - - createProcedure( - "testj2.testSameProcedureWithDifferentParameters", - "(OUT p1 VARCHAR(10))\nBEGIN" + "\nselect 2;" + "\nEND"); - - try (CallableStatement callableStatement = - sharedConnection.prepareCall("{ call testSameProcedureWithDifferentParameters(?, ?) }")) { - callableStatement.registerOutParameter(1, Types.VARCHAR); - callableStatement.setString(2, "mike"); - callableStatement.execute(); - } - sharedConnection.setCatalog("testj2"); - try (CallableStatement callableStatement = - sharedConnection.prepareCall("{ call testSameProcedureWithDifferentParameters(?, ?) }")) { - callableStatement.registerOutParameter(1, Types.VARCHAR); - callableStatement.setString(2, "mike"); - try { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS testj2"); + stmt.execute( + "CREATE PROCEDURE testj.testSameProcedureWithDifferentParameters(OUT p1 VARCHAR(10), IN p2 VARCHAR(10))\nBEGIN\nselect 1;\nEND"); + stmt.execute( + "CREATE PROCEDURE testj2.testSameProcedureWithDifferentParameters(OUT p1 VARCHAR(10))\nBEGIN\nselect 2;\nEND"); + + try (CallableStatement callableStatement = + sharedConnection.prepareCall("{ call testSameProcedureWithDifferentParameters(?, ?) }")) { + callableStatement.registerOutParameter(1, Types.VARCHAR); + callableStatement.setString(2, "mike"); callableStatement.execute(); - fail("Should've thrown an exception"); - } catch (SQLException sqlEx) { - assertEquals("42000", sqlEx.getSQLState()); } - } + sharedConnection.setCatalog("testj2"); + try (CallableStatement callableStatement = + sharedConnection.prepareCall("{ call testSameProcedureWithDifferentParameters(?, ?) }")) { + callableStatement.registerOutParameter(1, Types.VARCHAR); + callableStatement.setString(2, "mike"); + try { + callableStatement.execute(); + fail("Should've thrown an exception"); + } catch (SQLException sqlEx) { + assertEquals("42000", sqlEx.getSQLState()); + } + } - try (CallableStatement callableStatement = - sharedConnection.prepareCall("{ call testSameProcedureWithDifferentParameters(?) }")) { - callableStatement.registerOutParameter(1, Types.VARCHAR); - callableStatement.execute(); + try (CallableStatement callableStatement = + sharedConnection.prepareCall("{ call testSameProcedureWithDifferentParameters(?) }")) { + callableStatement.registerOutParameter(1, Types.VARCHAR); + callableStatement.execute(); + } + sharedConnection.setCatalog("testj"); + stmt.execute("DROP PROCEDURE testj.testSameProcedureWithDifferentParameters"); + stmt.executeUpdate("DROP DATABASE testj2"); } - sharedConnection.setCatalog("testj"); - sharedConnection.createStatement().executeUpdate("DROP DATABASE testj2"); } @Test public void testProcDecimalComa() throws Exception { - createProcedure( - "testProcDecimalComa", - "(decimalParam DECIMAL(18,0))\n" + "BEGIN\n" + " SELECT 1;\n" + "END"); try (CallableStatement callableStatement = sharedConnection.prepareCall("Call testProcDecimalComa(?)")) { callableStatement.setDouble(1, 18.0); @@ -532,8 +693,6 @@ public void testProcDecimalComa() throws Exception { @Test public void testFunctionCall() throws Exception { - createFunction( - "testFunctionCall", "(a float, b bigint, c int) RETURNS INT NO SQL\nBEGIN\nRETURN a;\nEND"); CallableStatement callableStatement = sharedConnection.prepareCall("{? = CALL testFunctionCall(?,?,?)}"); callableStatement.registerOutParameter(1, Types.INTEGER); @@ -631,13 +790,15 @@ public void testFunctionCall() throws Exception { @Test public void testCallOtherDb() throws Exception { - sharedConnection.createStatement().executeUpdate("CREATE DATABASE IF NOT EXISTS testj2"); - createProcedure("testj2.otherDbProcedure", "()\nBEGIN\nSELECT 1;\nEND "); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS testj2"); + stmt.execute("CREATE PROCEDURE testj2.otherDbProcedure()\nBEGIN\nSELECT 1;\nEND "); - try (Connection noDbConn = setConnection()) { - noDbConn.prepareCall("{call `testj2`.otherDbProcedure()}").execute(); + try (Connection noDbConn = setConnection()) { + noDbConn.prepareCall("{call `testj2`.otherDbProcedure()}").execute(); + } + stmt.executeUpdate("DROP DATABASE testj2"); } - sharedConnection.createStatement().executeUpdate("DROP DATABASE testj2"); } @Test @@ -647,16 +808,6 @@ public void testMultiResultset() throws Exception { cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - createProcedure( - "testInOutParam", - "(IN p1 VARCHAR(255), INOUT p2 INT)\n" - + "begin\n" - + " DECLARE z INT;\n" - + " SET z = p2 + 1;\n" - + " SET p2 = z;\n" - + " SELECT p1;\n" - + " SELECT CONCAT('todo ', p1);\n" - + "end"); try (CallableStatement callableStatement = sharedConnection.prepareCall("{call testInOutParam(?, ?)}")) { callableStatement.registerOutParameter(2, Types.INTEGER); @@ -682,10 +833,6 @@ public void testMultiResultset() throws Exception { @Test public void callFunctionWithNoParameters() throws SQLException { - createFunction( - "callFunctionWithNoParameters", - "()\n" + " RETURNS CHAR(50) DETERMINISTIC\n" + " RETURN 'mike';"); - CallableStatement callableStatement = sharedConnection.prepareCall("{? = call callFunctionWithNoParameters()}"); callableStatement.registerOutParameter(1, Types.VARCHAR); @@ -695,12 +842,6 @@ public void callFunctionWithNoParameters() throws SQLException { @Test public void testFunctionWith2parameters() throws SQLException { - createFunction( - "testFunctionWith2parameters", - "(s CHAR(20), s2 CHAR(20))\n" - + " RETURNS CHAR(50) DETERMINISTIC\n" - + " RETURN CONCAT(s,' and ', s2)"); - CallableStatement callableStatement = sharedConnection.prepareCall("{? = call testFunctionWith2parameters(?, ?)}"); callableStatement.registerOutParameter(1, Types.VARCHAR); @@ -712,12 +853,6 @@ public void testFunctionWith2parameters() throws SQLException { @Test public void testFunctionWithFixedParameters() throws SQLException { - createFunction( - "testFunctionWith2parameters", - "(s CHAR(20), s2 CHAR(20))\n" - + " RETURNS CHAR(50) DETERMINISTIC\n" - + " RETURN CONCAT(s,' and ', s2)"); - CallableStatement callableStatement = sharedConnection.prepareCall("{? = call testFunctionWith2parameters('mike', ?)}"); callableStatement.registerOutParameter(1, Types.VARCHAR); @@ -733,15 +868,6 @@ public void testResultsetWithInoutParameter() throws Exception { cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - createTable("testResultsetWithInoutParameterTb", "test VARCHAR(10)"); - createProcedure( - "testResultsetWithInoutParameter", - "(INOUT testValue VARCHAR(10))\n" - + "BEGIN\n" - + " insert into testResultsetWithInoutParameterTb(test) values (testValue);\n" - + " SELECT testValue;\n" - + " SET testValue = UPPER(testValue);\n" - + "END"); CallableStatement cstmt = sharedConnection.prepareCall("{call testResultsetWithInoutParameter(?)}"); cstmt.registerOutParameter(1, Types.VARCHAR); @@ -775,15 +901,6 @@ public void testSettingFixedParameter() throws SQLException { cancelForVersion(10, 2, 4); try (Connection connection = setConnection()) { - createProcedure( - "simpleproc", - "(IN inParam CHAR(20), INOUT inOutParam CHAR(20), OUT outParam CHAR(50))" - + " BEGIN\n" - + " SET inOutParam = UPPER(inOutParam);\n" - + " SET outParam = CONCAT('Hello, ', inOutParam, ' and ', inParam);" - + " SELECT 'a' FROM DUAL;\n" - + " END;"); - CallableStatement callableStatement = connection.prepareCall("{call simpleproc('mike', ?, ?)}"); callableStatement.registerOutParameter(1, Types.VARCHAR); @@ -801,15 +918,12 @@ public void testSettingFixedParameter() throws SQLException { @Test public void testNoParenthesisCall() throws Exception { - createProcedure("testProcedureParenthesis", "() BEGIN SELECT 1; END"); - createFunction("testFunctionParenthesis", "() RETURNS INT DETERMINISTIC RETURN 1;"); sharedConnection.prepareCall("{CALL testProcedureParenthesis}").execute(); sharedConnection.prepareCall("{? = CALL testFunctionParenthesis}").execute(); } @Test public void testProcLinefeed() throws Exception { - createProcedure("testProcLinefeed", "(\r\n)\r\n BEGIN SELECT 1; END"); CallableStatement callStmt = sharedConnection.prepareCall("{CALL testProcLinefeed()}"); callStmt.execute(); @@ -837,13 +951,16 @@ public void testHugeNumberOfParameters() throws Exception { } procDef.append(")\nBEGIN\nSELECT 1;\nEND"); - createProcedure("testHugeNumberOfParameters", procDef.toString()); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE PROCEDURE testHugeNumberOfParameters" + procDef.toString()); - try (CallableStatement callableStatement = - sharedConnection.prepareCall( - "{call testHugeNumberOfParameters(" + param.toString() + ")}")) { - callableStatement.registerOutParameter(274, Types.VARCHAR); - callableStatement.execute(); + try (CallableStatement callableStatement = + sharedConnection.prepareCall( + "{call testHugeNumberOfParameters(" + param.toString() + ")}")) { + callableStatement.registerOutParameter(274, Types.VARCHAR); + callableStatement.execute(); + } + stmt.execute("DROP PROCEDURE testHugeNumberOfParameters"); } } @@ -853,10 +970,6 @@ public void testStreamInOutWithName() throws Exception { cancelForVersion(10, 2, 2); cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - - createProcedure( - "testStreamInOutWithName", - "(INOUT mblob MEDIUMBLOB) BEGIN SELECT 1 FROM DUAL WHERE 1=0;\nEND"); try (CallableStatement cstmt = sharedConnection.prepareCall("{call testStreamInOutWithName(?)}")) { byte[] buffer = new byte[65]; @@ -910,10 +1023,6 @@ public void testDefinerCallableStatement() throws Exception { @Test public void testProcedureComment() throws Exception { - createProcedure( - "testProcedureComment", - "(a INT, b VARCHAR(32)) BEGIN SELECT CONCAT(CONVERT(a, CHAR(50)), b); END"); - try (CallableStatement callableStatement = sharedConnection.prepareCall( "{ call /*comment ? */ testj.testProcedureComment(?, " @@ -932,102 +1041,105 @@ public void testProcedureComment() throws Exception { @Test public void testCommentParser() throws Exception { - createProcedure( - "testCommentParser", - "(_ACTION varchar(20)," - + "`/*dumb-identifier-1*/` int," - + "\n`#dumb-identifier-2` int," - + "\n`--dumb-identifier-3` int," - + "\n_CLIENT_ID int, -- ABC" - + "\n_LOGIN_ID int, # DEF" - + "\n_WHERE varchar(2000)," - + "\n_SORT varchar(2000)," - + "\n out _SQL varchar(/* inline right here - oh my gosh! */ 8000)," - + "\n _SONG_ID int," - + "\n _NOTES varchar(2000)," - + "\n out _RESULT varchar(10)" - + "\n /*" - + "\n , -- Generic result parameter" - + "\n out _PERIOD_ID int, -- Returns the period_id. " - + "Useful when using @PREDEFLINK to return which is the last period" - + "\n _SONGS_LIST varchar(8000)," - + "\n _COMPOSERID int," - + "\n _PUBLISHERID int," - + "\n _PREDEFLINK int -- If the user is accessing through a " - + "predefined link: 0=none 1=last period" - + "\n */) BEGIN SELECT 1; END"); - - createProcedure( - "testCommentParser_1", - "(`/*id*/` /* before type 1 */ varchar(20)," - + "/* after type 1 */ OUT result2 DECIMAL(/*size1*/10,/*size2*/2) /* p2 */)BEGIN SELECT action, result; END"); - - sharedConnection - .prepareCall("{call testCommentParser(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}") - .close(); - ResultSet rs = - sharedConnection - .getMetaData() - .getProcedureColumns(sharedConnection.getCatalog(), null, "testCommentParser", "%"); - validateResult( - rs, - new String[] { - "_ACTION", - "/*dumb-identifier-1*/", - "#dumb-identifier-2", - "--dumb-identifier-3", - "_CLIENT_ID", - "_LOGIN_ID", - "_WHERE", - "_SORT", - "_SQL", - "_SONG_ID", - "_NOTES", - "_RESULT" - }, - new int[] { - Types.VARCHAR, - Types.INTEGER, - Types.INTEGER, - Types.INTEGER, - Types.INTEGER, - Types.INTEGER, - Types.VARCHAR, - Types.VARCHAR, - Types.VARCHAR, - Types.INTEGER, - Types.VARCHAR, - Types.VARCHAR - }, - new int[] {20, 10, 10, 10, 10, 10, 2000, 2000, 8000, 10, 2000, 10}, - new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - new int[] { - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnOut, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnIn, - DatabaseMetaData.procedureColumnOut - }); - - sharedConnection.prepareCall("{call testCommentParser_1(?, ?)}").close(); - rs = - sharedConnection - .getMetaData() - .getProcedureColumns(sharedConnection.getCatalog(), null, "testCommentParser_1", "%"); - validateResult( - rs, - new String[] {"/*id*/", "result2"}, - new int[] {Types.VARCHAR, Types.DECIMAL}, - new int[] {20, 10}, - new int[] {0, 2}, - new int[] {DatabaseMetaData.procedureColumnIn, DatabaseMetaData.procedureColumnOut}); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE PROCEDURE testCommentParser (" + + "_ACTION varchar(20)," + + "`/*dumb-identifier-1*/` int," + + "\n`#dumb-identifier-2` int," + + "\n`--dumb-identifier-3` int," + + "\n_CLIENT_ID int, -- ABC" + + "\n_LOGIN_ID int, # DEF" + + "\n_WHERE varchar(2000)," + + "\n_SORT varchar(2000)," + + "\n out _SQL varchar(/* inline right here - oh my gosh! */ 8000)," + + "\n _SONG_ID int," + + "\n _NOTES varchar(2000)," + + "\n out _RESULT varchar(10)" + + "\n /*" + + "\n , -- Generic result parameter" + + "\n out _PERIOD_ID int, -- Returns the period_id. " + + "Useful when using @PREDEFLINK to return which is the last period" + + "\n _SONGS_LIST varchar(8000)," + + "\n _COMPOSERID int," + + "\n _PUBLISHERID int," + + "\n _PREDEFLINK int -- If the user is accessing through a " + + "predefined link: 0=none 1=last period" + + "\n */) BEGIN SELECT 1; END"); + + stmt.execute( + "CREATE PROCEDURE testCommentParser_1(`/*id*/` /* before type 1 */ varchar(20)," + + "/* after type 1 */ OUT result2 DECIMAL(/*size1*/10,/*size2*/2) /* p2 */)BEGIN SELECT action, result; END"); + + sharedConnection + .prepareCall("{call testCommentParser(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}") + .close(); + ResultSet rs = + sharedConnection + .getMetaData() + .getProcedureColumns(sharedConnection.getCatalog(), null, "testCommentParser", "%"); + validateResult( + rs, + new String[] { + "_ACTION", + "/*dumb-identifier-1*/", + "#dumb-identifier-2", + "--dumb-identifier-3", + "_CLIENT_ID", + "_LOGIN_ID", + "_WHERE", + "_SORT", + "_SQL", + "_SONG_ID", + "_NOTES", + "_RESULT" + }, + new int[] { + Types.VARCHAR, + Types.INTEGER, + Types.INTEGER, + Types.INTEGER, + Types.INTEGER, + Types.INTEGER, + Types.VARCHAR, + Types.VARCHAR, + Types.VARCHAR, + Types.INTEGER, + Types.VARCHAR, + Types.VARCHAR + }, + new int[] {20, 10, 10, 10, 10, 10, 2000, 2000, 8000, 10, 2000, 10}, + new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + new int[] { + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnOut, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnIn, + DatabaseMetaData.procedureColumnOut + }); + + sharedConnection.prepareCall("{call testCommentParser_1(?, ?)}").close(); + rs = + sharedConnection + .getMetaData() + .getProcedureColumns(sharedConnection.getCatalog(), null, "testCommentParser_1", "%"); + validateResult( + rs, + new String[] {"/*id*/", "result2"}, + new int[] {Types.VARCHAR, Types.DECIMAL}, + new int[] {20, 10}, + new int[] {0, 2}, + new int[] {DatabaseMetaData.procedureColumnIn, DatabaseMetaData.procedureColumnOut}); + stmt.execute("DROP PROCEDURE testCommentParser"); + stmt.execute("DROP PROCEDURE testCommentParser_1"); + } } private void validateResult( @@ -1072,21 +1184,6 @@ public void testCallableNullSetters() throws Throwable { cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - createTable("testCallableNullSettersTable", "value_1 BIGINT PRIMARY KEY,value_2 VARCHAR(20)"); - createFunction( - "testCallableNullSetters", - "(value_1_v BIGINT, value_2_v VARCHAR(20)) RETURNS BIGINT " - + "DETERMINISTIC MODIFIES SQL DATA BEGIN " - + "INSERT INTO testCallableNullSettersTable VALUES (value_1_v,value_2_v); " - + "RETURN value_1_v; " - + "END;"); - createProcedure( - "testCallableNullSettersProc", - "(OUT value_1_v BIGINT, IN value_2_v BIGINT, IN value_3_v VARCHAR(20)) " - + "BEGIN " - + "INSERT INTO testCallableNullSettersTable VALUES (value_2_v,value_3_v); " - + "SET value_1_v = value_2_v; " - + "END;"); // Prepare the function call try (CallableStatement callable = sharedConnection.prepareCall("{? = call testCallableNullSetters(?,?)}")) { @@ -1236,55 +1333,37 @@ private void testSetter(CallableStatement callable) throws Throwable { @Test public void testCallableThrowException() throws Exception { - createTable("testCallableThrowException1", "value_1 BIGINT PRIMARY KEY", "ENGINE=InnoDB"); - createTable("testCallableThrowException2", "value_2 BIGINT PRIMARY KEY", "ENGINE=InnoDB"); - - sharedConnection - .createStatement() - .executeUpdate("INSERT INTO testCallableThrowException1 VALUES (1)"); - createFunction( - "test_function", - "() RETURNS BIGINT DETERMINISTIC MODIFIES SQL DATA BEGIN DECLARE max_value BIGINT; " - + "SELECT MAX(value_1) INTO max_value FROM testCallableThrowException2; RETURN max_value; END;"); - - try (CallableStatement callable = sharedConnection.prepareCall("{? = call test_function()}")) { - - callable.registerOutParameter(1, Types.BIGINT); - - try { - callable.executeUpdate(); - fail("impossible; we should never get here."); - } catch (SQLException sqlEx) { - assertEquals("42S22", sqlEx.getSQLState()); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("INSERT INTO testCallableThrowException1 VALUES (1)"); + try (CallableStatement callable = + sharedConnection.prepareCall("{? = call test_function()}")) { + callable.registerOutParameter(1, Types.BIGINT); + try { + callable.executeUpdate(); + fail("impossible; we should never get here."); + } catch (SQLException sqlEx) { + assertEquals("42S22", sqlEx.getSQLState()); + } } - } - sharedConnection.createStatement().execute("DROP TABLE IF EXISTS testCallableThrowException4"); - createTable("testCallableThrowException3", "value_1 BIGINT PRIMARY KEY", "ENGINE=InnoDB"); - sharedConnection - .createStatement() - .executeUpdate("INSERT INTO testCallableThrowException3 VALUES (1)"); - createTable( - "testCallableThrowException4", - "value_2 BIGINT PRIMARY KEY, " - + " FOREIGN KEY (value_2) REFERENCES testCallableThrowException3 (value_1) ON DELETE CASCADE", - "ENGINE=InnoDB"); - createFunction( - "test_function", - "(value BIGINT) RETURNS BIGINT DETERMINISTIC MODIFIES SQL DATA BEGIN " - + "INSERT INTO testCallableThrowException4 VALUES (value); RETURN value; END;"); - - try (CallableStatement callable = sharedConnection.prepareCall("{? = call test_function(?)}")) { - callable.registerOutParameter(1, Types.BIGINT); - callable.setLong(2, 1); - callable.executeUpdate(); - callable.setLong(2, 2); - try { + stmt.execute("INSERT INTO testCallableThrowException3 VALUES (1)"); + + try (CallableStatement callable = + sharedConnection.prepareCall("{? = call test_function2(?)}")) { + callable.registerOutParameter(1, Types.BIGINT); + callable.setLong(2, 1); callable.executeUpdate(); - fail("impossible; we should never get here."); - } catch (SQLException sqlEx) { - assertEquals("23000", sqlEx.getSQLState()); + callable.setLong(2, 2); + try { + callable.executeUpdate(); + fail("impossible; we should never get here."); + } catch (SQLException sqlEx) { + assertEquals("23000", sqlEx.getSQLState()); + } } + // stmt.execute("DROP FUNCTION IF EXISTS test_function"); + // stmt.execute("DROP TABLE IF EXISTS testCallableThrowException3"); + // stmt.execute("DROP TABLE IF EXISTS testCallableThrowException4"); } } @@ -1299,11 +1378,6 @@ public void testCallableStatementFormat() { @Test public void testFunctionWithFixedParameter() throws Exception { - createFunction( - "testFunctionWithFixedParameter", - "(a varchar(40), b bigint(20), c varchar(80)) RETURNS bigint(20) LANGUAGE SQL DETERMINISTIC " - + "MODIFIES SQL DATA COMMENT 'bbb' BEGIN RETURN 1; END; "); - try (CallableStatement callable = sharedConnection.prepareCall("{? = call testFunctionWithFixedParameter(?,101,?)}")) { callable.registerOutParameter(1, Types.BIGINT); @@ -1319,13 +1393,6 @@ public void testParameterNumber() throws Exception { cancelForVersion(10, 2, 2); cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - - createTable( - "TMIX91P", - "F01SMALLINT SMALLINT NOT NULL, F02INTEGER INTEGER,F03REAL REAL," - + "F04FLOAT FLOAT,F05NUMERIC31X4 NUMERIC(31,4), F06NUMERIC16X16 NUMERIC(16,16), F07CHAR_10 CHAR(10)," - + " F08VARCHAR_10 VARCHAR(10), F09CHAR_20 CHAR(20), F10VARCHAR_20 VARCHAR(20), F11DATE DATE," - + " F12DATETIME DATETIME, PRIMARY KEY (F01SMALLINT)"); Statement stmt = sharedConnection.createStatement(); stmt.executeUpdate( "INSERT INTO TMIX91P VALUES (1,1,1234567.12,1234567.12,111111111111111111111111111.1111,.111111111111111,'1234567890'," @@ -1338,14 +1405,6 @@ public void testParameterNumber() throws Exception { stmt.executeUpdate( "INSERT INTO TMIX91P VALUES (12,12,1234567.12,1234567.12,111222333.4444,.1234567890,'2234567891','2234567891','CHAR20'," + "'VARCHAR20VARCHAR20','2001-01-01','2001-01-01 01:01:01.111')"); - - createProcedure( - "MSQSPR100", - "\n( p1_in INTEGER , p2_in CHAR(20), OUT p3_out INTEGER, OUT p4_out CHAR(11))\nBEGIN " - + "\n SELECT F01SMALLINT,F02INTEGER, F11DATE,F12DATETIME,F03REAL \n FROM TMIX91P WHERE F02INTEGER = p1_in; " - + "\n SELECT F02INTEGER,F07CHAR_10,F08VARCHAR_10,F09CHAR_20 \n FROM TMIX91P WHERE F09CHAR_20 = p2_in ORDER BY F02INTEGER ; " - + "\n SET p3_out = 144; \n SET p4_out = 'CHARACTER11'; \n SELECT p3_out, p4_out; END"); - String sql = "{call MSQSPR100(1,'CHAR20',?,?)}"; CallableStatement cs = sharedConnection.prepareCall(sql); @@ -1356,17 +1415,6 @@ public void testParameterNumber() throws Exception { cs.execute(); cs.close(); - createProcedure( - "testParameterNumber_1", - "(OUT nfact VARCHAR(100), IN ccuenta VARCHAR(100),\nOUT ffact VARCHAR(100),\nOUT fdoc VARCHAR(100))\nBEGIN" - + "\nSET nfact = 'ncfact string';\nSET ffact = 'ffact string';\nSET fdoc = 'fdoc string';\nEND"); - - createProcedure( - "testParameterNumber_2", - "(IN ccuent1 VARCHAR(100), IN ccuent2 VARCHAR(100),\nOUT nfact VARCHAR(100),\nOUT ffact VARCHAR(100)," - + "\nOUT fdoc VARCHAR(100))\nBEGIN\nSET nfact = 'ncfact string';\nSET ffact = 'ffact string';\n" - + "SET fdoc = 'fdoc string';\nEND"); - Properties props = new Properties(); props.put("jdbcCompliantTruncation", "true"); props.put("useInformationSchema", "true"); @@ -1419,14 +1467,6 @@ public void testProcMultiDb() throws Exception { String originalCatalog = sharedConnection.getCatalog(); - sharedConnection - .createStatement() - .executeUpdate("CREATE DATABASE IF NOT EXISTS testProcMultiDb"); - - createProcedure( - "testProcMultiDb.testProcMultiDbProc", - "(x int, out y int)\nbegin\ndeclare z int;\nset z = x+1, y = z;\nend\n"); - CallableStatement callableStatement = null; try { callableStatement = @@ -1463,7 +1503,6 @@ public void testProcMultiDb() throws Exception { callableStatement.clearParameters(); callableStatement.close(); sharedConnection.setCatalog(originalCatalog); - sharedConnection.createStatement().executeUpdate("DROP DATABASE testProcMultiDb"); } } @@ -1473,12 +1512,6 @@ public void callProcSendNullInOut() throws Exception { cancelForVersion(10, 2, 2); cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - - createProcedure("testProcSendNullInOut_1", "(INOUT x INTEGER)\nBEGIN\nSET x = x + 1;\nEND"); - createProcedure( - "testProcSendNullInOut_2", "(x INTEGER, OUT y INTEGER)\nBEGIN\nSET y = x + 1;\nEND"); - createProcedure("testProcSendNullInOut_3", "(INOUT x INTEGER)\nBEGIN\nSET x = 10;\nEND"); - CallableStatement call = sharedConnection.prepareCall("{ call testProcSendNullInOut_1(?) }"); call.registerOutParameter(1, Types.INTEGER); call.setInt(1, 1); @@ -1537,9 +1570,6 @@ public void testCallExecuteErrorBatch() throws SQLException { */ @Test public void testFunctionWithSpace() throws SQLException { - createFunction( - "hello", - "()\n" + " RETURNS CHAR(50) DETERMINISTIC\n" + " RETURN CONCAT('Hello, !');"); CallableStatement callableStatement = sharedConnection.prepareCall("{? = call `hello` ()}"); callableStatement.registerOutParameter(1, Types.INTEGER); assertFalse(callableStatement.execute()); @@ -1557,14 +1587,6 @@ public void testOutputObjectType() throws Exception { cancelForVersion(10, 2, 2); cancelForVersion(10, 2, 3); cancelForVersion(10, 2, 4); - - createProcedure( - "issue425", - "(IN inValue TEXT, OUT testValue TEXT)\n" - + "BEGIN\n" - + " set testValue = CONCAT('o', inValue);\n" - + "END"); - // registering with VARCHAR Type CallableStatement cstmt = sharedConnection.prepareCall("{call issue425(?, ?)}"); cstmt.registerOutParameter(2, Types.VARCHAR); @@ -1591,9 +1613,6 @@ public void testOutputObjectType() throws Exception { @Test public void testOutputObjectTypeFunction() throws Exception { - createFunction( - "issue425f", "(a TEXT, b TEXT) RETURNS TEXT NO SQL\nBEGIN\nRETURN CONCAT(a, b);\nEND"); - // registering with VARCHAR Type CallableStatement cstmt = sharedConnection.prepareCall("{? = call issue425f(?, ?)}"); cstmt.registerOutParameter(1, Types.VARCHAR); @@ -1620,8 +1639,6 @@ public void testOutputObjectTypeFunction() throws Exception { @Test public void procedureCaching() throws SQLException { - createProcedure("cacheCall", "(IN inValue int)\n" + "BEGIN\n" + " /*do nothing*/ \n" + "END"); - CallableStatement st = sharedConnection.prepareCall("{call testj.cacheCall(?)}"); st.setInt(1, 2); st.execute(); @@ -1647,9 +1664,6 @@ public void procedureCaching() throws SQLException { @Test public void functionCaching() throws SQLException { - createFunction( - "hello2", - "()\n" + " RETURNS CHAR(50) DETERMINISTIC\n" + " RETURN CONCAT('Hello, !');"); CallableStatement st = sharedConnection.prepareCall("{? = call hello2()}"); st.registerOutParameter(1, Types.INTEGER); assertFalse(st.execute()); @@ -1674,9 +1688,6 @@ public void functionCaching() throws SQLException { @Test public void testTimestampParameterOutput() throws Exception { - createProcedure( - "CONJ791", "(IN a TEXT, OUT b DATETIME) \nBEGIN\nSET b := '2006-01-01 01:01:16';\nEND"); - // registering with VARCHAR Type CallableStatement cstmt = sharedConnection.prepareCall("{call CONJ791(?, ?)}"); cstmt.setString(1, "o"); diff --git a/src/test/java/org/mariadb/jdbc/StringUTFTest.java b/src/test/java/org/mariadb/jdbc/StringUTFTest.java index aac07f7a3..8612a4902 100644 --- a/src/test/java/org/mariadb/jdbc/StringUTFTest.java +++ b/src/test/java/org/mariadb/jdbc/StringUTFTest.java @@ -55,19 +55,27 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class StringUTFTest extends BaseTest { - /** - * Initialization. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable("stringutftest", "stringutf varchar(40)", "COLLATE='utf8mb4_general_ci'"); + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE stringutftest(stringutf varchar(40)) COLLATE='utf8mb4_general_ci'"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS stringutftest"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/TimeoutTest.java b/src/test/java/org/mariadb/jdbc/TimeoutTest.java index 4a4c7455e..1ff349742 100644 --- a/src/test/java/org/mariadb/jdbc/TimeoutTest.java +++ b/src/test/java/org/mariadb/jdbc/TimeoutTest.java @@ -80,7 +80,8 @@ public void resultSetAfterSocketTimeoutTest() { System.getenv("MAXSCALE_TEST_DISABLE") == null && System.getenv("APPVEYOR") == null && System.getenv("DOCKER_SOCKET") == null - && System.getenv("SKYSQL") == null); + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); Assume.assumeFalse(sharedIsAurora()); int went = 0; @@ -153,7 +154,7 @@ public void socketTimeoutTest() throws SQLException { @Test public void waitTimeoutStatementTest() throws SQLException, InterruptedException { - Assume.assumeFalse(sharedIsAurora()); + Assume.assumeTrue(!sharedIsAurora() && System.getenv("SKYSQL_HA") == null); try (Connection connection = setConnection()) { try (Statement statement = connection.createStatement()) { statement.execute("set session wait_timeout=1"); @@ -175,7 +176,7 @@ public void waitTimeoutStatementTest() throws SQLException, InterruptedException @Test public void waitTimeoutResultSetTest() throws SQLException, InterruptedException { - Assume.assumeFalse(sharedIsAurora()); + Assume.assumeTrue(!sharedIsAurora() && System.getenv("SKYSQL_HA") == null); try (Connection connection = setConnection()) { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 1"); diff --git a/src/test/java/org/mariadb/jdbc/TimezoneDaylightSavingTimeTest.java b/src/test/java/org/mariadb/jdbc/TimezoneDaylightSavingTimeTest.java index e687a9466..b82112f63 100644 --- a/src/test/java/org/mariadb/jdbc/TimezoneDaylightSavingTimeTest.java +++ b/src/test/java/org/mariadb/jdbc/TimezoneDaylightSavingTimeTest.java @@ -84,7 +84,8 @@ public class TimezoneDaylightSavingTimeTest extends BaseTest { */ @BeforeClass() public static void initClass() throws SQLException { - if (testSingleHost || !"true".equals(System.getenv("AURORA"))) { + if (testSingleHost + || ((System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null))) { try (Statement st = sharedConnection.createStatement()) { ResultSet rs = st.executeQuery( @@ -123,19 +124,53 @@ public static void initClass() throws SQLException { utcDateFormatSimple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); utcDateFormatSimple.setTimeZone(utcTimeZone); - createTable("daylightMysql", " tt DATE"); - if (doPrecisionTest) { - createTable("timeZoneTime", "id int, tt TIME(6)"); - createTable( - "ttimeTest", "id int not null primary key auto_increment, dd TIME(3), dd2 TIME(3)"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE daylightMysql(tt DATE)"); + stmt.execute( + "CREATE TABLE daylight(id int, t1 TIMESTAMP(6) NULL, t2 TIME(6), t3 DATETIME(6) , t4 DATE)"); + stmt.execute("CREATE TABLE daylight2(id int, tt TIMESTAMP(6))"); + stmt.execute( + "CREATE TABLE checkLocalDateTimefalsefalse(id int, tt DATETIME(6), tt2 TIME(6), tt3 varchar(100), tt4 varchar(100))"); + stmt.execute( + "CREATE TABLE checkLocalDateTimefalsetrue(id int, tt DATETIME(6), tt2 TIME(6), tt3 varchar(100), tt4 varchar(100))"); + stmt.execute( + "CREATE TABLE checkLocalDateTimetruetrue(id int, tt DATETIME(6), tt2 TIME(6), tt3 varchar(100), tt4 varchar(100))"); + stmt.execute( + "CREATE TABLE checkLocalDateTimetruefalse(id int, tt DATETIME(6), tt2 TIME(6), tt3 varchar(100), tt4 varchar(100))"); + stmt.execute("CREATE TABLE timeVerificationWithTimezone(time_field TIME)"); + stmt.execute("CREATE TABLE daylightCanada(id int, tt TIMESTAMP(6))"); + + if (doPrecisionTest) { + stmt.execute("CREATE TABLE timeZoneTime(id int, tt TIME(6))"); + stmt.execute( + "CREATE TABLE ttimeTest(id int not null primary key auto_increment, dd TIME(3), dd2 TIME(3))"); + } + stmt.execute("FLUSH TABLES"); } } } + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS daylightMysql"); + stmt.execute("DROP TABLE IF EXISTS daylight"); + stmt.execute("DROP TABLE IF EXISTS daylight2"); + stmt.execute("DROP TABLE IF EXISTS checkLocalDateTimefalsefalse"); + stmt.execute("DROP TABLE IF EXISTS checkLocalDateTimefalsetrue"); + stmt.execute("DROP TABLE IF EXISTS checkLocalDateTimetruetrue"); + stmt.execute("DROP TABLE IF EXISTS checkLocalDateTimetruefalse"); + stmt.execute("DROP TABLE IF EXISTS timeVerificationWithTimezone"); + stmt.execute("DROP TABLE IF EXISTS daylightCanada"); + stmt.execute("DROP TABLE IF EXISTS timeZoneTime"); + stmt.execute("DROP TABLE IF EXISTS ttimeTest"); + } + } /** Put the TimeZone to previous state. */ @AfterClass() public static void endClass() { - if (testSingleHost || !"true".equals(System.getenv("AURORA"))) { + if (testSingleHost + || ((System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null))) { TimeZone.setDefault(previousTimeZone); if (previousFormatLocale != null) { Locale.setDefault(previousFormatLocale); @@ -182,7 +217,7 @@ public void tearDown() { @Test public void testTimeStamp() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); TimeZone.setDefault(parisTimeZone); try (Connection connection = setConnection("&serverTimezone=Europe/Paris&useServerPrepStmts=true")) { @@ -216,7 +251,7 @@ public void testTimeStampUtc() throws SQLException { @Test public void testTimeStampUtcNow() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); TimeZone.setDefault(parisTimeZone); try (Connection connection = setConnection("&serverTimezone=UTC&useServerPrepStmts=true")) { TimeZone.setDefault(parisTimeZone); @@ -296,7 +331,7 @@ public void testDifferentTime() throws SQLException { @Test public void testTimeUtc() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(doPrecisionTest); TimeZone.setDefault(parisTimeZone); @@ -329,7 +364,7 @@ public void testTimeUtc() throws SQLException { @Test public void testTimeUtcNow() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); TimeZone.setDefault(parisTimeZone); try (Connection connection = setConnection("&serverTimezone=UTC")) { setSessionTimeZone(connection, "+00:00"); @@ -347,7 +382,7 @@ public void testTimeUtcNow() throws SQLException { @Test public void testTimeOffsetNowUseServer() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); try (Connection connection = setConnection("&useLegacyDatetimeCode=false&serverTimezone=+5:00")) { setSessionTimeZone(connection, "+5:00"); @@ -364,7 +399,7 @@ public void testTimeOffsetNowUseServer() throws SQLException { @Test public void testDifferentTimeZoneServer() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); try (Connection connection = setConnection("&serverTimezone=UTC")) { setSessionTimeZone(sharedConnection, "+00:00"); // timestamp timezone to parisTimeZone like server @@ -380,7 +415,7 @@ public void testDifferentTimeZoneServer() throws SQLException { @Test public void testTimeStampOffsetNowUseServer() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); try (Connection connection = setConnection("&serverTimezone=Europe/Paris")) { // timestamp timezone to parisTimeZone like server Timestamp currentTimeParis = new Timestamp(System.currentTimeMillis()); @@ -404,7 +439,7 @@ public void testDayLight() throws SQLException { } private void testDayLight(boolean legacy) throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(doPrecisionTest); Assume.assumeTrue(hasSuperPrivilege("testDayLight") && !sharedIsRewrite()); TimeZone.setDefault(parisTimeZone); @@ -413,9 +448,7 @@ private void testDayLight(boolean legacy) throws SQLException { "&useLegacyDatetimeCode=" + legacy + "&serverTimezone=Canada/Atlantic&sessionVariables=time_zone='Canada/Atlantic'")) { - - createTable("daylight", "id int, t1 TIMESTAMP(6) NULL, t2 TIME(6), t3 DATETIME(6) , t4 DATE"); - + sharedConnection.createStatement().execute("TRUNCATE daylight"); Calendar quarterBeforeChangingHour = Calendar.getInstance(TimeZone.getTimeZone("utc")); quarterBeforeChangingHour.clear(); quarterBeforeChangingHour.set(2015, Calendar.MARCH, 29, 0, 45, 0); @@ -772,7 +805,7 @@ public ResultSet checkResult(boolean legacy, boolean binaryProtocol) throws SQLE @Test public void testDayLightNotUtC() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(doPrecisionTest && hasSuperPrivilege("testDayLight") && !sharedIsRewrite()); TimeZone.setDefault(canadaTimeZone); try (Connection connection = setConnection("&serverTimezone=Europe/Paris")) { @@ -786,7 +819,6 @@ public void testDayLightNotUtC() throws SQLException { st.executeQuery("SET GLOBAL time_zone = 'Europe/Paris'"); rs = st.executeQuery("SHOW GLOBAL VARIABLES LIKE 'time_zone';"); assertTrue(rs.next()); - createTable("daylightCanada", "id int, tt TIMESTAMP(6)"); Calendar quarterBeforeChangingHour = Calendar.getInstance(TimeZone.getTimeZone("Canada/Atlantic")); @@ -843,7 +875,7 @@ public void testDayLightNotUtC() throws SQLException { @Test public void testDayLightWithClientTimeZoneDifferent() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(doPrecisionTest && !sharedIsRewrite()); TimeZone.setDefault(parisTimeZone); try (Connection connection = setConnection("&serverTimezone=UTC")) { @@ -859,8 +891,6 @@ public void testDayLightWithClientTimeZoneDifferent() throws SQLException { int offsetAfter = parisTimeZone.getOffset(quarterAfterChangingHour.getTimeInMillis()); assertEquals(offsetAfter, 7200000); - createTable("daylight2", "id int, tt TIMESTAMP(6)"); - Timestamp tt = new Timestamp(quarterBeforeChangingHour.getTimeInMillis()); tt.setNanos(123400000); PreparedStatement pst = connection.prepareStatement("INSERT INTO daylight2 VALUES (?, ?)"); @@ -898,7 +928,7 @@ public void testDayLightWithClientTimeZoneDifferent() throws SQLException { @Test public void testNoMysqlDayLightCompatibility() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeTrue(hasSuperPrivilege("testMysqlDayLightCompatibility")); TimeZone.setDefault(parisTimeZone); try (Connection connection = @@ -933,7 +963,7 @@ public void testNoMysqlDayLightCompatibility() throws SQLException { @Test public void checkSetLocalDateTimeNoOffset() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeFalse(!isMariadbServer() && strictBeforeVersion(5, 6)); checkSetLocalDateTime(true, true, "Europe/Paris"); checkSetLocalDateTime(true, false, "Europe/Paris"); @@ -943,7 +973,7 @@ public void checkSetLocalDateTimeNoOffset() throws SQLException { @Test public void checkSetLocalDateTimeOffset() throws SQLException { - Assume.assumeFalse("true".equals(System.getenv("AURORA"))); + Assume.assumeTrue(System.getenv("AURORA") == null && System.getenv("SKYSQL_HA") == null); Assume.assumeFalse(!isMariadbServer() && strictBeforeVersion(5, 6)); checkSetLocalDateTime(true, true, "+2:00"); checkSetLocalDateTime(true, false, "+2:00"); @@ -962,9 +992,6 @@ public void checkSetLocalDateTimeOffset() throws SQLException { */ public void checkSetLocalDateTime(boolean legacy, boolean useBinaryFormat, String timeZone) throws SQLException { - createTable( - "checkLocalDateTime" + legacy + useBinaryFormat, - " id int, tt DATETIME(6), tt2 TIME(6), tt3 varchar(100), tt4 varchar(100) "); TimeZone initialTimeZone = TimeZone.getDefault(); boolean isOffset = timeZone.startsWith("+"); if (isOffset) { @@ -1153,7 +1180,6 @@ public void timeVerificationWithTimezone() throws SQLException { TimeZone timeZone = TimeZone.getTimeZone("Asia/Kuala_Lumpur"); TimeZone.setDefault(timeZone); SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); - createTable("timeVerificationWithTimezone", "time_field TIME"); try (Connection conn = setConnection()) { diff --git a/src/test/java/org/mariadb/jdbc/TransactionTest.java b/src/test/java/org/mariadb/jdbc/TransactionTest.java index 878498f4c..039e9db02 100644 --- a/src/test/java/org/mariadb/jdbc/TransactionTest.java +++ b/src/test/java/org/mariadb/jdbc/TransactionTest.java @@ -58,29 +58,28 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class TransactionTest extends BaseTest { - /** - * Tables initialisation. - * - * @throws SQLException exception - */ - @Before - public void beforeTest() throws SQLException { - if (testSingleHost) { - Statement stmt = sharedConnection.createStatement(); - stmt.execute("drop table if exists tx_fore_key"); - stmt.execute("drop table if exists tx_prim_key"); - createTable("tx_prim_key", "id int not null primary key", "engine=innodb"); - createTable( - "tx_fore_key", - "id int not null primary key, id_ref int not null, " - + "foreign key (id_ref) references tx_prim_key(id) on delete restrict on update restrict", - "engine=innodb"); + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE tx_prim_key(id int not null primary key)"); + stmt.execute( + "CREATE TABLE tx_fore_key(" + + "id int not null primary key, " + + "id_ref int not null, " + + "foreign key (id_ref) references tx_prim_key(id) on delete restrict on update restrict)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS tx_fore_key"); + stmt.execute("DROP TABLE IF EXISTS tx_prim_key"); } } diff --git a/src/test/java/org/mariadb/jdbc/TruncateExceptionTest.java b/src/test/java/org/mariadb/jdbc/TruncateExceptionTest.java index 112620bda..cdcdbf99a 100644 --- a/src/test/java/org/mariadb/jdbc/TruncateExceptionTest.java +++ b/src/test/java/org/mariadb/jdbc/TruncateExceptionTest.java @@ -55,18 +55,29 @@ import static org.junit.Assert.*; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; public class TruncateExceptionTest extends BaseTest { - /** Tables initialisation. */ @BeforeClass() public static void initClass() throws SQLException { - createTable("TruncateExceptionTest", "id tinyint"); - createTable( - "TruncateExceptionTest2", "id tinyint not null primary key auto_increment, id2 tinyint "); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE TruncateExceptionTest(id tinyint)"); + stmt.execute( + "CREATE TABLE TruncateExceptionTest2(id tinyint not null primary key auto_increment, id2 tinyint)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS TruncateExceptionTest"); + stmt.execute("DROP TABLE IF EXISTS TruncateExceptionTest2"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/UnicodeTest.java b/src/test/java/org/mariadb/jdbc/UnicodeTest.java index d6348b9f1..7c82534f9 100644 --- a/src/test/java/org/mariadb/jdbc/UnicodeTest.java +++ b/src/test/java/org/mariadb/jdbc/UnicodeTest.java @@ -55,31 +55,35 @@ import static org.junit.Assert.assertEquals; import java.sql.*; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class UnicodeTest extends BaseTest { - /** - * Initialisation. - * - * @throws SQLException exception - */ @BeforeClass() public static void initClass() throws SQLException { - createTable( - "unicode_test", - "id int not null primary key auto_increment, test_text varchar(100)", - "charset utf8"); - createTable("umlaut_test", "id varchar(100), test_text varchar(100), t int", "charset utf8"); - createTable( - "unicode_test2", - "id int not null primary key auto_increment, test_text varchar(100)", - "charset=utf8"); - createTable( - "unicode_test3", - "id int not null primary key auto_increment, test_text varchar(100)", - "charset utf8mb4"); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE unicode_test(id int not null primary key auto_increment, test_text varchar(100)) charset utf8"); + stmt.execute( + "CREATE TABLE umlaut_test(id varchar(100), test_text varchar(100), t int) charset utf8"); + stmt.execute( + "CREATE TABLE unicode_test2(id int not null primary key auto_increment, test_text varchar(100)) charset utf8"); + stmt.execute( + "CREATE TABLE unicode_test3(id int not null primary key auto_increment, test_text varchar(100)) charset utf8mb4"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS unicode_test"); + stmt.execute("DROP TABLE IF EXISTS umlaut_test"); + stmt.execute("DROP TABLE IF EXISTS unicode_test2"); + stmt.execute("DROP TABLE IF EXISTS unicode_test3"); + } } @Test diff --git a/src/test/java/org/mariadb/jdbc/UpdateResultSetTest.java b/src/test/java/org/mariadb/jdbc/UpdateResultSetTest.java index 67e200aa2..24368ed33 100644 --- a/src/test/java/org/mariadb/jdbc/UpdateResultSetTest.java +++ b/src/test/java/org/mariadb/jdbc/UpdateResultSetTest.java @@ -58,11 +58,105 @@ import java.io.IOException; import java.io.InputStream; import java.sql.*; +import org.junit.AfterClass; import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; public class UpdateResultSetTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("CREATE TABLE testnoprimarykey(`id` INT NOT NULL,`t1` VARCHAR(50) NOT NULL)"); + stmt.execute( + "CREATE TABLE repeatedFieldUpdatable(t1 varchar(50) NOT NULL, t2 varchar(50), PRIMARY KEY (t1))"); + stmt.execute("CREATE TABLE updatePosTest(c text, id int primary key)"); + stmt.execute("CREATE TABLE deleteRows(c text, id int primary key)"); + stmt.execute("CREATE TABLE cancelRowUpdatesTest(c text, id int primary key)"); + stmt.execute("CREATE TABLE testMoveToInsertRow(t2 text, t1 text, id int primary key)"); + stmt.execute("CREATE TABLE refreshRow(id int not null primary key, strm blob)"); + stmt.execute("CREATE TABLE insertNoRow(id int not null primary key, strm blob)"); + stmt.execute("CREATE TABLE updateBlob(id int not null primary key, strm blob)"); + stmt.execute( + "CREATE TABLE testUpdateChangingMultiplePrimaryKey(" + + "`id` INT NOT NULL," + + "`id2` INT NOT NULL," + + "`t1` VARCHAR(50)," + + "PRIMARY KEY (`id`,`id2`))"); + stmt.execute( + "CREATE TABLE PrimaryGenerated(" + + "`id` INT NOT NULL AUTO_INCREMENT," + + "`t1` VARCHAR(50) NOT NULL," + + "`t2` VARCHAR(50) NULL default 'default-value'," + + "PRIMARY KEY (`id`))"); + stmt.execute( + "CREATE TABLE testMultipleTable1(`id1` INT NOT NULL AUTO_INCREMENT,`t1` VARCHAR(50) NULL,PRIMARY KEY (`id1`))"); + stmt.execute( + "CREATE TABLE testMultipleTable2(`id2` INT NOT NULL AUTO_INCREMENT,`t2` VARCHAR(50) NULL,PRIMARY KEY (`id2`))"); + stmt.execute( + "CREATE TABLE testOneNoTable(`id1` INT NOT NULL AUTO_INCREMENT,`t1` VARCHAR(50) NULL,PRIMARY KEY (`id1`))"); + stmt.execute( + "CREATE TABLE UpdateWithoutPrimary(`id` INT NOT NULL AUTO_INCREMENT," + + "`t1` VARCHAR(50) NOT NULL," + + "`t2` VARCHAR(50) NULL default 'default-value'," + + "PRIMARY KEY (`id`))"); + stmt.execute( + "CREATE TABLE testUpdateWhenFetch(" + + "`id` INT NOT NULL AUTO_INCREMENT," + + "`t1` VARCHAR(50) NOT NULL," + + "`t2` VARCHAR(50) NULL default 'default-value'," + + "PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8"); + stmt.execute( + "CREATE TABLE testPrimaryGeneratedDefault(" + + "`id` INT NOT NULL AUTO_INCREMENT," + + "`t1` VARCHAR(50) NOT NULL default 'default-value1'," + + "`t2` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," + + "PRIMARY KEY (`id`))"); + stmt.execute( + "CREATE TABLE testDelete(`id` INT NOT NULL," + + "`id2` INT NOT NULL," + + "`t1` VARCHAR(50)," + + "PRIMARY KEY (`id`,`id2`))"); + stmt.execute( + "CREATE TABLE testMultipleDatabase(`id1` INT NOT NULL AUTO_INCREMENT,`t1` VARCHAR(50) NULL,PRIMARY KEY (`id1`))"); + if (isMariadbServer() && minVersion(10, 2)) { + stmt.execute( + "CREATE TABLE `testDefaultUUID` (" + + "`column1` varchar(40) NOT NULL DEFAULT uuid()," + + "`column2` varchar(100) DEFAULT NULL," + + " PRIMARY KEY (`column1`))"); + } + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.executeQuery("DROP TABLE IF EXISTS `testDefaultUUID`"); + stmt.execute("DROP TABLE IF EXISTS testnoprimarykey"); + stmt.execute("DROP TABLE IF EXISTS repeatedFieldUpdatable"); + stmt.execute("DROP TABLE IF EXISTS updatePosTest"); + stmt.execute("DROP TABLE IF EXISTS deleteRows"); + stmt.execute("DROP TABLE IF EXISTS cancelRowUpdatesTest"); + stmt.execute("DROP TABLE IF EXISTS testMoveToInsertRow"); + stmt.execute("DROP TABLE IF EXISTS refreshRow"); + stmt.execute("DROP TABLE IF EXISTS insertNoRow"); + stmt.execute("DROP TABLE IF EXISTS updateBlob"); + stmt.execute("DROP TABLE IF EXISTS testUpdateChangingMultiplePrimaryKey"); + stmt.execute("DROP TABLE IF EXISTS PrimaryGenerated"); + stmt.execute("DROP TABLE IF EXISTS testMultipleTable1"); + stmt.execute("DROP TABLE IF EXISTS testMultipleTable2"); + stmt.execute("DROP TABLE IF EXISTS testOneNoTable"); + stmt.execute("DROP TABLE IF EXISTS UpdateWithoutPrimary"); + stmt.execute("DROP TABLE IF EXISTS testUpdateWhenFetch"); + stmt.execute("DROP TABLE IF EXISTS testPrimaryGeneratedDefault"); + stmt.execute("DROP TABLE IF EXISTS testDelete"); + stmt.execute("DROP TABLE IF EXISTS testMultipleDatabase"); + } + } + /** * Test error message when no primary key. * @@ -70,7 +164,6 @@ public class UpdateResultSetTest extends BaseTest { */ @Test public void testNoPrimaryKey() throws Exception { - createTable("testnoprimarykey", "`id` INT NOT NULL," + "`t1` VARCHAR(50) NOT NULL"); Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO testnoprimarykey VALUES (1, 't1'), (2, 't2')"); @@ -117,15 +210,6 @@ public void testNoDatabase() throws Exception { @Test public void testMultipleTable() throws Exception { - - createTable( - "testMultipleTable1", - "`id1` INT NOT NULL AUTO_INCREMENT," + "`t1` VARCHAR(50) NULL," + "PRIMARY KEY (`id1`)"); - - createTable( - "testMultipleTable2", - "`id2` INT NOT NULL AUTO_INCREMENT," + "`t2` VARCHAR(50) NULL," + "PRIMARY KEY (`id2`)"); - Statement stmt = sharedConnection.createStatement(); stmt.executeQuery("INSERT INTO testMultipleTable1(t1) values ('1')"); stmt.executeQuery("INSERT INTO testMultipleTable2(t2) values ('2')"); @@ -153,10 +237,6 @@ public void testMultipleTable() throws Exception { @Test public void testOneNoTable() throws Exception { - createTable( - "testOneNoTable", - "`id1` INT NOT NULL AUTO_INCREMENT," + "`t1` VARCHAR(50) NULL," + "PRIMARY KEY (`id1`)"); - Statement stmt = sharedConnection.createStatement(); stmt.executeQuery("INSERT INTO testOneNoTable(t1) values ('1')"); @@ -186,53 +266,42 @@ public void testMultipleDatabase() throws Exception { Statement stmt = sharedConnection.createStatement(); try { - stmt.execute("DROP DATABASE testConnectorJ"); - } catch (SQLException sqle) { - // eat - } - - stmt.execute("CREATE DATABASE testConnectorJ"); - createTable( - sharedConnection.getCatalog() + ".testMultipleDatabase", - "`id1` INT NOT NULL AUTO_INCREMENT," + "`t1` VARCHAR(50) NULL," + "PRIMARY KEY (`id1`)"); - - createTable( - "testConnectorJ.testMultipleDatabase", - "`id2` INT NOT NULL AUTO_INCREMENT," + "`t2` VARCHAR(50) NULL," + "PRIMARY KEY (`id2`)"); - - stmt.executeQuery( - "INSERT INTO " + sharedConnection.getCatalog() + ".testMultipleDatabase(t1) values ('1')"); - stmt.executeQuery("INSERT INTO testConnectorJ.testMultipleDatabase(t2) values ('2')"); - - try (PreparedStatement preparedStatement = - sharedConnection.prepareStatement( - "SELECT * FROM " - + sharedConnection.getCatalog() - + ".testMultipleDatabase, testConnectorJ.testMultipleDatabase", - ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_UPDATABLE)) { - ResultSet rs = preparedStatement.executeQuery(); - assertTrue(rs.next()); - try { - rs.updateString("t1", "new value"); - fail("must have failed since there is different database"); - } catch (SQLException sqle) { - assertTrue( - sqle.getMessage(), - sqle.getMessage().contains("The result-set contains more than one database")); + stmt.execute("CREATE DATABASE testConnectorJ"); + stmt.execute( + "CREATE TABLE testConnectorJ.testMultipleDatabase(" + + "`id2` INT NOT NULL AUTO_INCREMENT,`t2` VARCHAR(50) NULL,PRIMARY KEY (`id2`))"); + + stmt.executeQuery( + "INSERT INTO " + + sharedConnection.getCatalog() + + ".testMultipleDatabase(t1) values ('1')"); + stmt.executeQuery("INSERT INTO testConnectorJ.testMultipleDatabase(t2) values ('2')"); + + try (PreparedStatement preparedStatement = + sharedConnection.prepareStatement( + "SELECT * FROM " + + sharedConnection.getCatalog() + + ".testMultipleDatabase, testConnectorJ.testMultipleDatabase", + ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_UPDATABLE)) { + ResultSet rs = preparedStatement.executeQuery(); + assertTrue(rs.next()); + try { + rs.updateString("t1", "new value"); + fail("must have failed since there is different database"); + } catch (SQLException sqle) { + assertTrue( + sqle.getMessage(), + sqle.getMessage().contains("The result-set contains more than one database")); + } } + } catch (SQLException sqle) { + stmt.execute("DROP DATABASE testConnectorJ"); } } @Test public void testMeta() throws Exception { - createTable( - "UpdateWithoutPrimary", - "`id` INT NOT NULL AUTO_INCREMENT," - + "`t1` VARCHAR(50) NOT NULL," - + "`t2` VARCHAR(50) NULL default 'default-value'," - + "PRIMARY KEY (`id`)"); - Statement stmt = sharedConnection.createStatement(); stmt.executeQuery("INSERT INTO UpdateWithoutPrimary(t1,t2) values ('1-1','1-2')"); @@ -306,14 +375,6 @@ public void testMeta() throws Exception { @Test public void testUpdateWhenFetch() throws Exception { - createTable( - "testUpdateWhenFetch", - "`id` INT NOT NULL AUTO_INCREMENT," - + "`t1` VARCHAR(50) NOT NULL," - + "`t2` VARCHAR(50) NULL default 'default-value'," - + "PRIMARY KEY (`id`)", - "DEFAULT CHARSET=utf8"); - final Statement stmt = sharedConnection.createStatement(); PreparedStatement pstmt = sharedConnection.prepareStatement("INSERT INTO testUpdateWhenFetch(t1,t2) values (?, ?)"); @@ -373,13 +434,6 @@ public void testUpdateWhenFetch() throws Exception { @Test public void testPrimaryGenerated() throws Exception { - createTable( - "PrimaryGenerated", - "`id` INT NOT NULL AUTO_INCREMENT," - + "`t1` VARCHAR(50) NOT NULL," - + "`t2` VARCHAR(50) NULL default 'default-value'," - + "PRIMARY KEY (`id`)"); - Statement stmt = sharedConnection.createStatement(); int[] autoInc = setAutoInc(); @@ -441,12 +495,6 @@ public void testPrimaryGenerated() throws Exception { @Test public void testPrimaryGeneratedDefault() throws Exception { - createTable( - "testPrimaryGeneratedDefault", - "`id` INT NOT NULL AUTO_INCREMENT," - + "`t1` VARCHAR(50) NOT NULL default 'default-value1'," - + "`t2` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," - + "PRIMARY KEY (`id`)"); int[] autoInc = setAutoInc(); try (PreparedStatement preparedStatement = sharedConnection.prepareStatement( @@ -491,13 +539,6 @@ public void testPrimaryGeneratedDefault() throws Exception { @Test public void testDelete() throws Exception { - createTable( - "testDelete", - "`id` INT NOT NULL," - + "`id2` INT NOT NULL," - + "`t1` VARCHAR(50)," - + "PRIMARY KEY (`id`,`id2`)"); - Statement stmt = sharedConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.execute("INSERT INTO testDelete values (1,-1,'1'), (2,-2,'2'), (3,-3,'3')"); @@ -549,13 +590,6 @@ public void testDelete() throws Exception { @Test public void testUpdateChangingMultiplePrimaryKey() throws Exception { - createTable( - "testUpdateChangingMultiplePrimaryKey", - "`id` INT NOT NULL," - + "`id2` INT NOT NULL," - + "`t1` VARCHAR(50)," - + "PRIMARY KEY (`id`,`id2`)"); - Statement stmt = sharedConnection.createStatement(); stmt.execute( "INSERT INTO testUpdateChangingMultiplePrimaryKey values (1,-1,'1'), (2,-2,'2'), (3,-3,'3')"); @@ -600,8 +634,6 @@ public void testUpdateChangingMultiplePrimaryKey() throws Exception { @Test public void updateBlob() throws SQLException, IOException { - createTable("updateBlob", "id int not null primary key, strm blob"); - PreparedStatement stmt = sharedConnection.prepareStatement("insert into updateBlob (id, strm) values (?,?)"); byte[] theBlob = {1, 2, 3, 4, 5, 6}; @@ -700,7 +732,6 @@ public void updateResultSetMeta() throws SQLException { @Test public void insertNoRow() throws SQLException { - createTable("insertNoRow", "id int not null primary key, strm blob"); Statement st = sharedConnection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); @@ -718,7 +749,6 @@ public void insertNoRow() throws SQLException { @Test public void refreshRow() throws SQLException { - createTable("refreshRow", "id int not null primary key, strm blob"); Statement st = sharedConnection.createStatement( @@ -760,8 +790,6 @@ public void refreshRow() throws SQLException { @Test public void testMoveToInsertRow() throws SQLException { - createTable("testMoveToInsertRow", "t2 text, t1 text, id int primary key"); - try (PreparedStatement preparedStatement = sharedConnection.prepareStatement( "select id, t1, t2 from testMoveToInsertRow", @@ -848,8 +876,6 @@ public void testMoveToInsertRow() throws SQLException { @Test public void cancelRowUpdatesTest() throws SQLException { - createTable("cancelRowUpdatesTest", "c text, id int primary key"); - Statement st = sharedConnection.createStatement(); st.executeUpdate( "INSERT INTO cancelRowUpdatesTest(id,c) values (1,'1'), (2,'2'),(3,'3'),(4,'4')"); @@ -882,8 +908,6 @@ public void cancelRowUpdatesTest() throws SQLException { @Test public void deleteRowsTest() throws SQLException { - createTable("deleteRows", "c text, id int primary key"); - Statement st = sharedConnection.createStatement(); st.executeUpdate("INSERT INTO deleteRows(id,c) values (1,'1'), (2,'2'),(3,'3'),(4,'4')"); @@ -912,8 +936,6 @@ public void deleteRowsTest() throws SQLException { @Test public void updatePosTest() throws SQLException { - createTable("updatePosTest", "c text, id int primary key"); - Statement st = sharedConnection.createStatement(); st.executeUpdate("INSERT INTO updatePosTest(id,c) values (1,'1')"); @@ -981,9 +1003,6 @@ public void updatePosTest() throws SQLException { */ @Test public void repeatedFieldUpdatable() throws SQLException { - createTable( - "repeatedFieldUpdatable", "t1 varchar(50) NOT NULL, t2 varchar(50), PRIMARY KEY (t1)"); - Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into repeatedFieldUpdatable values ('gg', 'hh'), ('jj', 'll')"); @@ -1002,12 +1021,6 @@ public void repeatedFieldUpdatable() throws SQLException { public void updatableDefaultPrimaryField() throws SQLException { Assume.assumeTrue(isMariadbServer() && minVersion(10, 2)); Statement stmt = sharedConnection.createStatement(); - stmt.executeQuery("DROP TABLE IF EXISTS `testDefaultUUID`"); - stmt.execute( - "CREATE TABLE `testDefaultUUID` (" - + "`column1` varchar(40) NOT NULL DEFAULT uuid()," - + "`column2` varchar(100) DEFAULT NULL," - + " PRIMARY KEY (`column1`))"); String sql = "SELECT t.* FROM testDefaultUUID t WHERE 1 = 2"; try (PreparedStatement pstmt = sharedConnection.prepareStatement( diff --git a/src/test/java/org/mariadb/jdbc/failover/AllowMasterDownTest.java b/src/test/java/org/mariadb/jdbc/failover/AllowMasterDownTest.java index d18ce18a8..9214f4f8a 100644 --- a/src/test/java/org/mariadb/jdbc/failover/AllowMasterDownTest.java +++ b/src/test/java/org/mariadb/jdbc/failover/AllowMasterDownTest.java @@ -56,21 +56,35 @@ import static org.junit.Assert.assertTrue; import java.sql.*; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mariadb.jdbc.BaseTest; public class AllowMasterDownTest extends BaseTest { + @BeforeClass() + public static void initClass() throws SQLException { + afterClass(); + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute( + "CREATE TABLE checkMetaData(xx tinyint(1) primary key auto_increment, yy year(4), zz bit, uu smallint)"); + stmt.execute("FLUSH TABLES"); + } + } + + @AfterClass + public static void afterClass() throws SQLException { + try (Statement stmt = sharedConnection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS checkMetaData"); + } + } + private String masterDownUrl; /** Initialisation. */ @Before public void init() { Assume.assumeTrue(testSingleHost); - Assume.assumeTrue(System.getenv("SKYSQL") == null); + Assume.assumeTrue(System.getenv("SKYSQL") == null && System.getenv("SKYSQL_HA") == null); if (testSingleHost) { masterDownUrl = "jdbc:mariadb:replication//" @@ -128,9 +142,6 @@ public void masterDownAutoCommit() { @Test public void masterDownGetMeta() { try (Connection connection = DriverManager.getConnection(masterDownUrl)) { - createTable( - "checkMetaData", - "xx tinyint(1) primary key auto_increment, yy year(4), zz bit, uu smallint"); DatabaseMetaData meta = connection.getMetaData(); meta.getColumns(null, null, "checkMetaData", null); Assert.fail("Must have thrown a connectionException"); @@ -142,9 +153,6 @@ public void masterDownGetMeta() { @Test public void masterDownGetMetaRead() throws SQLException { try (Connection connection = DriverManager.getConnection(masterDownUrl)) { - createTable( - "checkMetaData", - "xx tinyint(1) primary key auto_increment, yy year(4), zz bit, uu smallint"); connection.setReadOnly(true); DatabaseMetaData meta = connection.getMetaData(); ResultSet rs = meta.getColumns(null, null, "checkMetaData", null); diff --git a/src/test/java/org/mariadb/jdbc/failover/BaseMonoServer.java b/src/test/java/org/mariadb/jdbc/failover/BaseMonoServer.java index 2b084cba8..9c63703fe 100644 --- a/src/test/java/org/mariadb/jdbc/failover/BaseMonoServer.java +++ b/src/test/java/org/mariadb/jdbc/failover/BaseMonoServer.java @@ -107,7 +107,7 @@ public void relaunchWithErrorWhenInTransaction() throws Throwable { "create table baseReplicationTransaction" + jobId + " (id int not null primary key auto_increment, test VARCHAR(10))"); - + st.execute("FLUSH TABLES"); connection.setAutoCommit(false); st.execute("INSERT INTO baseReplicationTransaction" + jobId + "(test) VALUES ('test')"); int masterServerId = getServerId(connection); @@ -141,6 +141,7 @@ public void failoverRelaunchedWhenSelect() throws Throwable { + jobId + " (id int not null primary key , amount int not null) " + "ENGINE = InnoDB"); + st.execute("FLUSH TABLES"); stopProxy(masterServerId, 2); try { st.execute("SELECT * from selectFailover" + jobId); @@ -173,6 +174,7 @@ public void failoverRelaunchedWhenInTransaction() throws Throwable { + jobId + " (id int not null primary key , amount int not null) " + "ENGINE = InnoDB"); + st.execute("FLUSH TABLES"); connection.setAutoCommit(false); st.execute("INSERT INTO selectFailoverTrans" + jobId + " VALUES (0,0)"); stopProxy(masterServerId, 2); diff --git a/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java b/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java index ab55a3eb8..35218188b 100644 --- a/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java +++ b/src/test/java/org/mariadb/jdbc/failover/BaseReplication.java @@ -77,6 +77,7 @@ public void failoverReplicaToMasterPrepareStatement() throws Throwable { "create table replicationFailoverBinary" + jobId + " (id int not null primary key auto_increment, test VARCHAR(10))"); + stmt.execute("FLUSH TABLES"); stmt.execute("insert into replicationFailoverBinary" + jobId + "(test) values ('Harriba !')"); final int masterServerId = getServerId(connection); connection.setReadOnly(true); @@ -266,6 +267,7 @@ public void writeToReplicaAfterFailover() throws Throwable { "create table writeToReplica" + jobId + " (id int not null primary key , amount int not null) ENGINE = InnoDB"); + st.execute("FLUSH TABLES"); st.execute("insert into writeToReplica" + jobId + " (id, amount) VALUE (1 , 100)"); int masterServerId = getServerId(connection); diff --git a/src/test/java/org/mariadb/jdbc/failover/MonoServerFailoverTest.java b/src/test/java/org/mariadb/jdbc/failover/MonoServerFailoverTest.java index fb0898d43..77148f85e 100644 --- a/src/test/java/org/mariadb/jdbc/failover/MonoServerFailoverTest.java +++ b/src/test/java/org/mariadb/jdbc/failover/MonoServerFailoverTest.java @@ -76,7 +76,10 @@ public static void beforeClass2() { /** Initialisation. */ @Before public void init() { - Assume.assumeTrue(initialUrl != null && System.getenv("SKYSQL") == null); + Assume.assumeTrue( + initialUrl != null + && System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null); defaultUrl = initialUrl; currentType = HaMode.NONE; } @@ -164,7 +167,9 @@ public void checkAutoReconnectDeconnection() throws Throwable { @Test public void isValidConnectionThatIsKilledExternally() throws Throwable { Assume.assumeTrue( - System.getenv("SKYSQL") == null && System.getenv("MAXSCALE_TEST_DISABLE") == null); + System.getenv("SKYSQL") == null + && System.getenv("SKYSQL_HA") == null + && System.getenv("MAXSCALE_TEST_DISABLE") == null); try (Connection connection = getNewConnection()) { connection.setCatalog("mysql"); Protocol protocol = getProtocolFromConnection(connection); @@ -184,7 +189,7 @@ public void checkPrepareStatement() throws Throwable { Statement stmt = connection.createStatement(); stmt.execute("drop table if exists failt1"); stmt.execute("create table failt1 (id int not null primary key auto_increment, tt int)"); - + stmt.execute("FLUSH TABLES"); PreparedStatement preparedStatement = connection.prepareStatement("insert into failt1(id, tt) values (?,?)"); diff --git a/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java b/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java index e7bccad19..26514c216 100644 --- a/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java +++ b/src/test/java/org/mariadb/jdbc/failover/ReplicationFailoverTest.java @@ -107,6 +107,7 @@ public void assureReadOnly(boolean useAlias) throws SQLException { "create table replicationDelete" + jobId + " (id int not null primary key auto_increment, test VARCHAR(10))"); + stmt.execute("FLUSH TABLES"); connection.setReadOnly(true); assertTrue(connection.isReadOnly()); try { @@ -233,6 +234,7 @@ public void commitExecutionOnReplica() throws SQLException { try (Connection conn = getNewConnection()) { Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE IF NOT EXISTS commitExecution(id int, val varchar(256))"); + stmt.execute("FLUSH TABLES"); stmt.execute("TRUNCATE TABLE commitExecution"); stmt.execute("INSERT INTO commitExecution value (1, 'test')"); conn.setAutoCommit(false); diff --git a/src/test/java/org/mariadb/jdbc/internal/protocol/tls/HostnameVerifierImplTest.java b/src/test/java/org/mariadb/jdbc/internal/protocol/tls/HostnameVerifierImplTest.java index 66459d397..c7831b249 100644 --- a/src/test/java/org/mariadb/jdbc/internal/protocol/tls/HostnameVerifierImplTest.java +++ b/src/test/java/org/mariadb/jdbc/internal/protocol/tls/HostnameVerifierImplTest.java @@ -69,11 +69,11 @@ public void verifyCn() throws Exception { verifyExceptionEqual( "a.test.com", cert, - "DNS host \"a.test.com\" doesn't correspond to " + "certificate CN \"test.com\""); + "DNS host \"a.test.com\" doesn't correspond to certificate CN \"test.com\""); verifyExceptionEqual( "other.com", cert, - "DNS host \"other.com\" doesn't correspond to " + "certificate CN \"test.com\""); + "DNS host \"other.com\" doesn't correspond to certificate CN \"test.com\""); } @Test @@ -104,9 +104,7 @@ public void verifyNonAsciiCn() throws Exception { + "-----END CERTIFICATE-----\n"); verifier.verify("😎.com", cert, -1); verifyExceptionEqual( - "a.😎.com", - cert, - "DNS host \"a.😎.com\" doesn't " + "correspond to certificate CN \"😎.com\""); + "a.😎.com", cert, "DNS host \"a.😎.com\" doesn't correspond to certificate CN \"😎.com\""); } @Test @@ -237,7 +235,7 @@ public void verifyMultipleCn() throws Exception { verifyExceptionEqual( "test2.org", cert, - "DNS host \"test2.org\" doesn't correspond to " + "certificate CN \"test1.org\""); + "DNS host \"test2.org\" doesn't correspond to certificate CN \"test1.org\""); } @Test @@ -272,15 +270,13 @@ public void verifyWilcardCn() throws Exception { + "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" + "-----END CERTIFICATE-----\n"); verifyExceptionEqual( - "foo.com", - cert, - "DNS host \"foo.com\" doesn't correspond to certificate " + "CN \"*.foo.com\""); + "foo.com", cert, "DNS host \"foo.com\" doesn't correspond to certificate CN \"*.foo.com\""); verifier.verify("www.foo.com", cert, -1); verifier.verify("花子.foo.com", cert, -1); verifyExceptionEqual( "a.b.foo.com", cert, - "DNS host \"a.b.foo.com\" doesn't correspond to " + "certificate CN \"*.foo.com\""); + "DNS host \"a.b.foo.com\" doesn't correspond to certificate CN \"*.foo.com\""); } @Test From dddc1b40706305f3ddcd7ef532e8b0d07fea0a5c Mon Sep 17 00:00:00 2001 From: rusher Date: Mon, 23 Nov 2020 15:59:59 +0100 Subject: [PATCH 25/25] bump 2.7.1 version --- CHANGELOG.md | 16 ++++++++++++++++ pom.xml | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff3115373..d8378397a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Change Log +## [2.7.1](https://github.com/mariadb-corporation/mariadb-connector-j/tree/2.7.1) (23 Nov. 2020) +[Full Changelog](https://github.com/mariadb-corporation/mariadb-connector-j/compare/2.7.0...2.7.1) + +* CONJ-834 use of BULK batch is conditioned by capability, not checking server version +* CONJ-835 GSS Imports set in OSGI Bundle +* CONJ-839 Wrong exception message when rewriteBatchedStatements is enabled +* CONJ-841 ResultSetMetaData::getColumnTypeName() returns incorrect type name for LONGTEXT +* CONJ-842 Byte array parameters are now send as long data +* CONJ-837 prepared statement cache leak on ResultSet CONCUR_UPDATABLE concurrency +* CONJ-843 ParameterMetaData::getParameterType for CallableStatement parameter return expected "BINARY" value for BINARY type + +minor: +* CONJ-845 test suite now test SkySQL with replication setting +* CONJ-838 have a 'replica' alias for 'slave' connection option + + ## [2.7.0](https://github.com/mariadb-corporation/mariadb-connector-j/tree/2.7.0) (24 Sep. 2020) [Full Changelog](https://github.com/mariadb-corporation/mariadb-connector-j/compare/2.6.2...2.7.0) diff --git a/pom.xml b/pom.xml index 6da00fe66..da316591f 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,7 @@ mariadb-java-client jar mariadb-java-client - 2.7.1-SNAPSHOT + 2.7.1 JDBC driver for MariaDB and MySQL https://mariadb.com/kb/en/mariadb/about-mariadb-connector-j/