From b7370a80512fab9f94533889a7cd7acf34e6f1f5 Mon Sep 17 00:00:00 2001 From: v-xiangs Date: Wed, 31 May 2017 11:52:36 -0700 Subject: [PATCH 01/68] wrapper test for prepared statement 42 and callable statement 42 --- .../jdbc/unit/statement/Wrapper42Test.java | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/Wrapper42Test.java diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/Wrapper42Test.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/Wrapper42Test.java new file mode 100644 index 000000000..8322deb60 --- /dev/null +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/Wrapper42Test.java @@ -0,0 +1,96 @@ +/* + * Microsoft JDBC Driver for SQL Server + * + * Copyright(c) Microsoft Corporation All rights reserved. + * + * This program is made available under the terms of the MIT License. See the LICENSE file in the project root for more information. + */ +package com.microsoft.sqlserver.jdbc.unit.statement; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; +import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement42; +import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; +import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement42; +import com.microsoft.sqlserver.testframework.AbstractTest; + +/** + * Test SQLServerPreparedSatement42 and SQLServerCallableSatement42 classes + * + */ +@RunWith(JUnitPlatform.class) +public class Wrapper42Test extends AbstractTest { + static Connection connection = null; + double javaVersion = Double.parseDouble(System.getProperty("java.specification.version")); + static int major; + static int minor; + + /** + * Tests creation of SQLServerPreparedSatement42 object + * + * @throws SQLException + */ + @Test + public void PreparedSatement42Test() throws SQLException { + String sql = "SELECT SUSER_SNAME()"; + + PreparedStatement pstmt = connection.prepareStatement(sql); + + if (1.8d <= javaVersion && 4 == major && 2 == minor) { + assertTrue(pstmt instanceof SQLServerPreparedStatement42); + } + else { + assertTrue(pstmt instanceof SQLServerPreparedStatement); + } + } + + /** + * Tests creation of SQLServerCallableStatement42 object + * + * @throws SQLException + */ + @Test + public void CallableStatement42Test() throws SQLException { + String sql = "SELECT SUSER_SNAME()"; + + CallableStatement cstmt = connection.prepareCall(sql); + + if (1.8d <= javaVersion && 4 == major && 2 == minor) { + assertTrue(cstmt instanceof SQLServerCallableStatement42); + } + else { + assertTrue(cstmt instanceof SQLServerCallableStatement); + } + } + + @BeforeAll + private static void setupConnection() throws SQLException { + connection = DriverManager.getConnection(connectionString); + + DatabaseMetaData metadata = connection.getMetaData(); + major = metadata.getJDBCMajorVersion(); + minor = metadata.getJDBCMinorVersion(); + } + + @AfterAll + private static void terminateVariation() throws SQLException { + if (null != connection) { + connection.close(); + } + } + +} From 965cb4e4dc88311435785d12c32ae11c77ca4594 Mon Sep 17 00:00:00 2001 From: v-xiangs Date: Wed, 31 May 2017 12:34:45 -0700 Subject: [PATCH 02/68] add test for SQLServerResultSet42 --- .../resultset/ResultSetWrapper42Test.java | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetWrapper42Test.java diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetWrapper42Test.java b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetWrapper42Test.java new file mode 100644 index 000000000..78612674e --- /dev/null +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetWrapper42Test.java @@ -0,0 +1,82 @@ +/* + * Microsoft JDBC Driver for SQL Server + * + * Copyright(c) Microsoft Corporation All rights reserved. + * + * This program is made available under the terms of the MIT License. See the LICENSE file in the project root for more information. + */ +package com.microsoft.sqlserver.jdbc.resultset; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +import com.microsoft.sqlserver.jdbc.SQLServerResultSet42; +import com.microsoft.sqlserver.testframework.AbstractTest; + +/** + * Test SQLServerResultSet42 class + * + */ +@RunWith(JUnitPlatform.class) +public class ResultSetWrapper42Test extends AbstractTest { + static Connection connection = null; + double javaVersion = Double.parseDouble(System.getProperty("java.specification.version")); + static int major; + static int minor; + + /** + * Tests creation of SQLServerResultSet42 object + * + * @throws SQLException + */ + @Test + public void SQLServerResultSet42Test() throws SQLException { + String sql = "SELECT SUSER_SNAME()"; + + ResultSet rs = null; + try { + rs = connection.createStatement().executeQuery(sql); + + if (1.8d <= javaVersion && 4 == major && 2 == minor) { + assertTrue(rs instanceof SQLServerResultSet42); + } + else { + assertTrue(rs instanceof SQLServerResultSet); + } + } + finally { + if (null != rs) { + rs.close(); + } + } + } + + @BeforeAll + private static void setupConnection() throws SQLException { + connection = DriverManager.getConnection(connectionString); + + DatabaseMetaData metadata = connection.getMetaData(); + major = metadata.getJDBCMajorVersion(); + minor = metadata.getJDBCMinorVersion(); + } + + @AfterAll + private static void terminateVariation() throws SQLException { + if (null != connection) { + connection.close(); + } + } + +} From 7cdbf33cf4e4467a5027a0a51e535bce0f92637e Mon Sep 17 00:00:00 2001 From: v-xiangs Date: Fri, 14 Jul 2017 10:23:18 -0700 Subject: [PATCH 03/68] populate table with prepared statement --- .../jdbc/bulkCopy/BulkCopyTestSetUp.java | 4 +- .../testframework/AbstractSQLGenerator.java | 1 + .../testframework/DBPreparedStatement.java | 22 +++++++ .../sqlserver/testframework/DBTable.java | 57 ++++++++++++++++++- 4 files changed, 80 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java index 30fbe46a0..2b23bf836 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java @@ -14,6 +14,7 @@ import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.DBPreparedStatement; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable;; @@ -37,7 +38,8 @@ static void setUpSourceTable() { stmt = con.createStatement(); sourceTable = new DBTable(true); stmt.createTable(sourceTable); - stmt.populateTable(sourceTable); + DBPreparedStatement pstmt = new DBPreparedStatement(con); + pstmt.populateTable(sourceTable); } finally { con.close(); diff --git a/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java b/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java index dd7dc1c4b..e10ad94e0 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java @@ -22,6 +22,7 @@ public abstract class AbstractSQLGenerator {// implements ISQLGenerator { protected static final String PRIMARY_KEY = "PRIMARY KEY"; protected static final String DEFAULT = "DEFAULT"; protected static final String COMMA = ","; + protected static final String QUESTION_MARK = "?"; // FIXME: Find good word for '. Better replaced by wrapIdentifier. protected static final String TICK = "'"; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBPreparedStatement.java b/src/test/java/com/microsoft/sqlserver/testframework/DBPreparedStatement.java index 6ff5fa6f1..99d9c5ab3 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBPreparedStatement.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBPreparedStatement.java @@ -30,6 +30,10 @@ public DBPreparedStatement(DBConnection dbconnection) { } /** + * set up internal PreparedStatement with query + * + * @param query + * @return * @throws SQLException * */ @@ -84,4 +88,22 @@ public DBResultSet executeQuery() throws SQLException { return dbresultSet; } + /** + * populate table with values using prepared statement + * + * @param table + * @return true if table is populated + */ + public boolean populateTable(DBTable table) { + return table.populateTableWithPreparedStatement(this); + } + + /** + * + * @return + * @throws SQLException + */ + public boolean execute() throws SQLException { + return pstmt.execute(); + } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java b/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java index 90d6ae3bc..7c931b784 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java @@ -11,6 +11,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.sql.JDBCType; +import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -143,7 +144,7 @@ private void addColumns(boolean unicode) { public String getTableName() { return tableName; } - + public List getColumns() { return this.columns; } @@ -156,7 +157,7 @@ public List getColumns() { public String getEscapedTableName() { return escapedTableName; } - + public String getDefinitionOfColumns() { return tableDefinition; } @@ -234,7 +235,7 @@ else if (VariableLengthType.ScaleOnly == column.getSqlType().getVariableLengthTy tableDefinition = tableDefinition.substring(0, indexOfLastComma); sb.add(tableDefinition); - + sb.add(CLOSE_BRACKET); return sb.toString(); } @@ -257,6 +258,56 @@ boolean populateTable(DBStatement dbstatement) { return false; } + /** + * using prepared statement to populate table with values + * + * @param dbstatement + * @return + */ + boolean populateTableWithPreparedStatement(DBPreparedStatement dbPStmt) { + try { + populateValues(); + + // create the insertion query + StringJoiner sb = new StringJoiner(SPACE_CHAR); + sb.add("INSERT"); + sb.add("INTO"); + sb.add(escapedTableName); + sb.add("VALUES"); + sb.add(OPEN_BRACKET); + for (int colNum = 0; colNum < totalColumns; colNum++) { + sb.add(QUESTION_MARK); + + if (colNum < totalColumns - 1) { + sb.add(COMMA); + } + } + sb.add(CLOSE_BRACKET); + String sql = sb.toString(); + + dbPStmt.prepareStatement(sql); + + // insert data + for (int i = 0; i < totalRows; i++) { + for (int colNum = 0; colNum < totalColumns; colNum++) { + if (passDataAsHex(colNum)) { + ((PreparedStatement) dbPStmt.product()).setBytes(colNum + 1, ((byte[]) (getColumn(colNum).getRowValue(i)))); + } + else { + dbPStmt.setObject(colNum + 1, String.valueOf(getColumn(colNum).getRowValue(i))); + } + } + dbPStmt.execute(); + } + + return true; + } + catch (SQLException ex) { + fail(ex.getMessage()); + } + return false; + } + private void populateValues() { // generate values for all columns for (int i = 0; i < totalColumns; i++) { From 4213afcf9df0b297752182131262a3f46d5c4f3c Mon Sep 17 00:00:00 2001 From: Michael Newcomb Date: Fri, 1 Sep 2017 16:50:21 -0400 Subject: [PATCH 04/68] TimeoutTimer: Check for destroyed TheadGroup Running a query that uses a timer can cause an IllegalThreadStateException if the underlying ThreadGroup has been destroyed --- .../com/microsoft/sqlserver/jdbc/IOBuffer.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index e70f04bbf..9fcf57bfe 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -7122,13 +7122,21 @@ final class TimeoutTimer implements Runnable { private volatile Future task; private static final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { - private final ThreadGroup tg = new ThreadGroup(threadGroupName); - private final String threadNamePrefix = tg.getName() + "-"; + private final AtomicReference tgr = new AtomicReference<>(); private final AtomicInteger threadNumber = new AtomicInteger(0); @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(tg, r, threadNamePrefix + threadNumber.incrementAndGet()); + public Thread newThread(Runnable r) + { + ThreadGroup tg = tgr.get(); + + if (tg == null || tg.isDestroyed()) + { + tg = new ThreadGroup(threadGroupName); + tgr.set(tg); + } + + Thread t = new Thread(tg, r, tg.getName() + "-" + threadNumber.incrementAndGet()); t.setDaemon(true); return t; } From 9da95c5ac9134ce2717900d36806fdd08d0b84c1 Mon Sep 17 00:00:00 2001 From: Michael Newcomb Date: Fri, 1 Sep 2017 17:04:07 -0400 Subject: [PATCH 05/68] TimeoutTimer: Forgot reference Forgot to add AtomicReference --- src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index 9fcf57bfe..4c0aed0fa 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -64,6 +64,7 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; From 6789eb6fc86fe5b31a1ffd769f87065a616de2c2 Mon Sep 17 00:00:00 2001 From: Gord Thompson Date: Tue, 19 Sep 2017 19:06:17 -0600 Subject: [PATCH 06/68] recognize CallableStatement parameter names with leading '@' --- .../jdbc/SQLServerCallableStatement.java | 6 ++ .../CallableStatementTest.java | 63 ++++++++++++++++++- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java index 40a77be15..15777f4ca 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java @@ -1451,6 +1451,12 @@ public NClob getNClob(String parameterName) throws SQLException { if (paramNames != null) l = paramNames.size(); + // handle `@name` as well as `name`, since `@name` is what's returned + // by DatabaseMetaData#getProcedureColumns + if (columnName.startsWith("@")) { + columnName = columnName.substring(1, columnName.length()); + } + // In order to be as accurate as possible when locating parameter name // indexes, as well as be deterministic when running on various client // locales, we search for parameter names using the following scheme: diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java index d0271714d..9c682e849 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -1,9 +1,12 @@ package com.microsoft.sqlserver.jdbc.callablestatement; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; @@ -17,6 +20,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; +import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.Utils; @@ -28,6 +32,7 @@ public class CallableStatementTest extends AbstractTest { private static String tableNameGUID = "uniqueidentifier_Table"; private static String outputProcedureNameGUID = "uniqueidentifier_SP"; private static String setNullProcedureName = "CallableStatementTest_setNull_SP"; + private static String inputParamsProcedureName = "CallableStatementTest_inputParams_SP"; private static Connection connection = null; private static Statement stmt = null; @@ -45,10 +50,12 @@ public static void setupTest() throws SQLException { Utils.dropTableIfExists(tableNameGUID, stmt); Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); Utils.dropProcedureIfExists(setNullProcedureName, stmt); + Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); createGUIDTable(); createGUIDStoredProcedure(); - createSetNullPreocedure(); + createSetNullProcedure(); + createInputParamsProcedure(); } /** @@ -133,6 +140,44 @@ public void getSetNullWithTypeVarchar() throws SQLException { } } + + /** + * recognize parameter names with and without leading '@' + * + * @throws SQLException + */ + @Test + public void inputParamsTest() throws SQLException { + String call = "{CALL " + inputParamsProcedureName + " (?,?)}"; + ResultSet rs = null; + + // the historical way: no leading '@', parameter names respected (not positional) + CallableStatement cs1 = connection.prepareCall(call); + cs1.setString("p2", "bar"); + cs1.setString("p1", "foo"); + rs = cs1.executeQuery(); + rs.next(); + assertEquals("foobar", rs.getString(1)); + + // the "new" way: leading '@', parameter names still respected (not positional) + CallableStatement cs2 = connection.prepareCall(call); + cs2.setString("@p2", "world!"); + cs2.setString("@p1", "Hello "); + rs = cs2.executeQuery(); + rs.next(); + assertEquals("Hello world!", rs.getString(1)); + + // sanity check: unrecognized parameter name + CallableStatement cs3 = connection.prepareCall(call); + try { + cs3.setString("@whatever", "junk"); + fail("SQLServerException should have been thrown"); + } catch (SQLServerException sse) { + // expected + } + + } + /** * Cleanup after test * @@ -143,6 +188,7 @@ public static void cleanup() throws SQLException { Utils.dropTableIfExists(tableNameGUID, stmt); Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); Utils.dropProcedureIfExists(setNullProcedureName, stmt); + Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); if (null != stmt) { stmt.close(); @@ -162,7 +208,20 @@ private static void createGUIDTable() throws SQLException { stmt.execute(sql); } - private static void createSetNullPreocedure() throws SQLException { + private static void createSetNullProcedure() throws SQLException { stmt.execute("create procedure " + setNullProcedureName + " (@p1 nvarchar(255), @p2 nvarchar(255) output) as select @p2=@p1 return 0"); } + + private static void createInputParamsProcedure() throws SQLException { + String sql = + "CREATE PROCEDURE [dbo].[CallableStatementTest_inputParams_SP] " + + " @p1 nvarchar(max) = N'parameter1', " + + " @p2 nvarchar(max) = N'parameter2' " + + "AS " + + "BEGIN " + + " SET NOCOUNT ON; " + + " SELECT @p1 + @p2 AS result; " + + "END "; + stmt.execute(sql); + } } From fbf569c27298757a72cc8dd7c6b8a202f7619097 Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Thu, 21 Sep 2017 14:22:28 -0700 Subject: [PATCH 07/68] Revert "removing javax.xml.bind package dependency " --- .../microsoft/sqlserver/jdbc/IOBuffer.java | 10 ++- .../SQLServerAeadAes256CbcHmac256Factory.java | 4 +- ...umnEncryptionCertificateStoreProvider.java | 3 +- .../jdbc/SQLServerSymmetricKeyCache.java | 4 +- .../jdbc/AlwaysEncrypted/AESetup.java | 3 +- .../jdbc/connection/DriverVersionTest.java | 8 +-- .../jdbc/connection/WarningTest.java | 15 +--- .../BatchExecutionWithNullTest.java | 4 +- .../sqlserver/testframework/util/Util.java | 69 ------------------- 9 files changed, 21 insertions(+), 99 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index 86041682b..4369d3c00 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -72,6 +72,7 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; +import javax.xml.bind.DatatypeConverter; final class TDS { // TDS protocol versions @@ -4955,7 +4956,7 @@ else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength) isShortValue = columnPair.getValue().precision <= DataTypes.SHORT_VARTYPE_MAX_BYTES; isNull = (null == currentObject); if (currentObject instanceof String) - dataLength = isNull ? 0 : (ParameterUtils.HexToBin(currentObject.toString())).length; + dataLength = isNull ? 0 : (toByteArray(currentObject.toString())).length; else dataLength = isNull ? 0 : ((byte[]) currentObject).length; if (!isShortValue) { @@ -4974,7 +4975,7 @@ else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength) if (dataLength > 0) { writeInt(dataLength); if (currentObject instanceof String) - writeBytes(ParameterUtils.HexToBin(currentObject.toString())); + writeBytes(toByteArray(currentObject.toString())); else writeBytes((byte[]) currentObject); } @@ -4988,7 +4989,7 @@ else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength) else { writeShort((short) dataLength); if (currentObject instanceof String) - writeBytes(ParameterUtils.HexToBin(currentObject.toString())); + writeBytes(toByteArray(currentObject.toString())); else writeBytes((byte[]) currentObject); } @@ -5025,6 +5026,9 @@ private void writeTVPSqlVariantHeader(int length, writeByte(probBytes); } + private static byte[] toByteArray(String s) { + return DatatypeConverter.parseHexBinary(s); + } void writeTVPColumnMetaData(TVP value) throws SQLServerException { boolean isShortValue; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAeadAes256CbcHmac256Factory.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAeadAes256CbcHmac256Factory.java index c62a35728..8f71ec6b6 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAeadAes256CbcHmac256Factory.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerAeadAes256CbcHmac256Factory.java @@ -11,9 +11,9 @@ import static java.nio.charset.StandardCharsets.UTF_8; import java.text.MessageFormat; -import java.util.Base64; import java.util.concurrent.ConcurrentHashMap; +import javax.xml.bind.DatatypeConverter; /** * Factory for SQLServerAeadAes256CbcHmac256Algorithm @@ -38,7 +38,7 @@ SQLServerEncryptionAlgorithm create(SQLServerSymmetricKey columnEncryptionKey, } StringBuilder factoryKeyBuilder = new StringBuilder(); - factoryKeyBuilder.append(Base64.getEncoder().encodeToString(new String(columnEncryptionKey.getRootKey(), UTF_8).getBytes())); + factoryKeyBuilder.append(DatatypeConverter.printBase64Binary(new String(columnEncryptionKey.getRootKey(), UTF_8).getBytes())); factoryKeyBuilder.append(":"); factoryKeyBuilder.append(encryptionType); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java index 19aa45b2e..4a38df69e 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java @@ -25,6 +25,7 @@ import java.util.Enumeration; import java.util.Locale; +import javax.xml.bind.DatatypeConverter; /** * The implementation of the key store provider for the Windows Certificate Store. This class enables using keys stored in the Windows Certificate @@ -134,7 +135,7 @@ private String getThumbPrint(X509Certificate cert) throws NoSuchAlgorithmExcepti byte[] der = cert.getEncoded(); md.update(der); byte[] digest = md.digest(); - return Util.bytesToHexString(digest, digest.length); + return DatatypeConverter.printHexBinary(digest); } private CertificateDetails getCertificateByThumbprint(String storeLocation, diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSymmetricKeyCache.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSymmetricKeyCache.java index c0b56ece5..76b886786 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSymmetricKeyCache.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSymmetricKeyCache.java @@ -12,13 +12,13 @@ import static java.util.concurrent.TimeUnit.SECONDS; import java.text.MessageFormat; -import java.util.Base64; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; +import javax.xml.bind.DatatypeConverter; class CacheClear implements Runnable { @@ -98,7 +98,7 @@ SQLServerSymmetricKey getKey(EncryptionKeyInfo keyInfo, String keyLookupValue; keyLookupValuebuffer.append(":"); - keyLookupValuebuffer.append(Base64.getEncoder().encodeToString((new String(keyInfo.encryptedKey, UTF_8)).getBytes())); + keyLookupValuebuffer.append(DatatypeConverter.printBase64Binary((new String(keyInfo.encryptedKey, UTF_8)).getBytes())); keyLookupValuebuffer.append(":"); keyLookupValuebuffer.append(keyInfo.keyStoreName); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java index 452e85bae..6fc795a98 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -21,6 +21,7 @@ import java.util.LinkedList; import java.util.Properties; +import javax.xml.bind.DatatypeConverter; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -718,7 +719,7 @@ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storePro String cekSql = null; byte[] key = storeProvider.encryptColumnEncryptionKey(javaKeyAliases, "RSA_OAEP", valuesDefault); cekSql = "CREATE COLUMN ENCRYPTION KEY " + cekName + " WITH VALUES " + "(COLUMN_MASTER_KEY = " + cmkName - + ", ALGORITHM = 'RSA_OAEP', ENCRYPTED_VALUE = 0x" + Util.bytesToHexString(key, key.length) + ")" + ";"; + + ", ALGORITHM = 'RSA_OAEP', ENCRYPTED_VALUE = 0x" + DatatypeConverter.printHexBinary(key) + ")" + ";"; stmt.execute(cekSql); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DriverVersionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DriverVersionTest.java index bbd0ca5d6..911120ebb 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DriverVersionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DriverVersionTest.java @@ -12,14 +12,13 @@ import java.util.Arrays; import java.util.Random; +import javax.xml.bind.DatatypeConverter; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; -import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.util.Util; /** * This test validates PR #342. In this PR, DatatypeConverter#parseHexBinary is replaced with type casting. This tests validates if the behavior @@ -39,13 +38,12 @@ public class DriverVersionTest extends AbstractTest { /** * validates version byte array generated by the original method and type casting reminds the same. - * @throws SQLServerException */ @Test - public void testConnectionDriver() throws SQLServerException { + public void testConnectionDriver() { // the original way to create version byte array String interfaceLibVersion = generateInterfaceLibVersion(); - byte originalVersionBytes[] = Util.hexStringToByte(interfaceLibVersion); + byte originalVersionBytes[] = DatatypeConverter.parseHexBinary(interfaceLibVersion); String originalBytes = Arrays.toString(originalVersionBytes); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java index 8b99699b1..66ee1111b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java @@ -13,8 +13,6 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLWarning; -import java.util.Arrays; -import java.util.List; import java.util.Properties; import org.junit.jupiter.api.Test; @@ -42,18 +40,9 @@ public void testWarnings() throws SQLException { } conn.setClientInfo(info2); warn = conn.getWarnings(); - for (int i = 0; i < 5; i++) { - boolean found = false; - List list = Arrays.asList(infoArray); - for (String word : list) { - if (warn.toString().contains(word)) { - found = true; - break; - } - } - assertTrue(found, "warning : '" + warn.toString() + "' not found!"); + for (int i = 4; i >= 0; i--) { + assertTrue(warn.toString().contains(infoArray[i]), "Warnings not found!"); warn = warn.getNextWarning(); - found = false; } conn.clearWarnings(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java index 77a7ac54f..ceb0bde9b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -116,10 +116,8 @@ public void testSetup() throws TestAbortedException, Exception { } @AfterAll - public static void terminateVariation() throws TestAbortedException, Exception { + public static void terminateVariation() throws SQLException { - assumeTrue(13 <= new DBConnection(connectionString).getServerVersion(), - "Aborting test case as SQL Server version is not compatible with Always encrypted "); SQLServerStatement stmt = (SQLServerStatement) connection.createStatement(); Utils.dropTableIfExists("esimple", stmt); diff --git a/src/test/java/com/microsoft/sqlserver/testframework/util/Util.java b/src/test/java/com/microsoft/sqlserver/testframework/util/Util.java index 20c47c7d3..f1e5167c4 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/util/Util.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/util/Util.java @@ -11,7 +11,6 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData; -import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.jdbc.SQLServerStatementColumnEncryptionSetting; /** @@ -290,72 +289,4 @@ public static boolean supportJDBC42(Connection con) throws SQLException { SQLServerDatabaseMetaData meta = (SQLServerDatabaseMetaData) con.getMetaData(); return (meta.getJDBCMajorVersion() >= 4 && meta.getJDBCMinorVersion() >= 2); } - - /** - * - * @param b - * byte value - * @param length - * length of the array - * @return - */ - final static char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; - - public static String bytesToHexString(byte[] b, - int length) { - StringBuilder sb = new StringBuilder(length * 2); - for (int i = 0; i < length; i++) { - int hexVal = b[i] & 0xFF; - sb.append(hexChars[(hexVal & 0xF0) >> 4]); - sb.append(hexChars[(hexVal & 0x0F)]); - } - return sb.toString(); - } - - - /** - * conversion routine valid values 0-9 a-f A-F throws exception when failed to convert - * - * @param value - * charArray - * @return - * @throws SQLServerException - */ - static byte CharToHex(char value) throws SQLServerException { - byte ret = 0; - if (value >= 'A' && value <= 'F') { - ret = (byte) (value - 'A' + 10); - } - else if (value >= 'a' && value <= 'f') { - ret = (byte) (value - 'a' + 10); - } - else if (value >= '0' && value <= '9') { - ret = (byte) (value - '0'); - } - else { - throw new IllegalArgumentException("The string is not in a valid hex format. "); - } - return ret; - } - - /** - * Converts a string to an array of bytes - * - * @param hexV - * a hexized string representation of bytes - * @return - * @throws SQLServerException - */ - public static byte[] hexStringToByte(String hexV) throws SQLServerException { - int len = hexV.length(); - char orig[] = hexV.toCharArray(); - if ((len % 2) != 0) { - throw new IllegalArgumentException("The string is not in a valid hex format: " + hexV); - } - byte[] bin = new byte[len / 2]; - for (int i = 0; i < len / 2; i++) { - bin[i] = (byte) ((CharToHex(orig[2 * i]) << 4) + CharToHex(orig[2 * i + 1])); - } - return bin; - } } From 0047c3b62e56a79ae0f210b1ead20a050137ff99 Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Thu, 21 Sep 2017 16:56:02 -0700 Subject: [PATCH 08/68] Revert "Removing deprecated APIs in java 9" --- .../java/com/microsoft/sqlserver/jdbc/DDC.java | 4 ++-- .../com/microsoft/sqlserver/jdbc/FailOverInfo.java | 2 +- .../sqlserver/jdbc/SQLServerBulkCSVFileRecord.java | 3 ++- .../sqlserver/jdbc/SQLServerConnection.java | 14 +++++++------- .../sqlserver/jdbc/SQLServerDataSource.java | 2 +- .../jdbc/SQLServerDataSourceObjectFactory.java | 5 ++--- .../microsoft/sqlserver/jdbc/SQLServerDriver.java | 2 +- .../microsoft/sqlserver/jdbc/SQLServerSQLXML.java | 9 +++------ .../com/microsoft/sqlserver/jdbc/SqlVariant.java | 2 +- .../java/com/microsoft/sqlserver/jdbc/dtv.java | 2 +- 10 files changed, 21 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java index 091b314ee..6bf3af9e6 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java @@ -232,7 +232,7 @@ static final Object convertFloatToObject(float floatVal, return new BigDecimal(Float.toString(floatVal)); case FLOAT: case DOUBLE: - return (Float.valueOf(floatVal)).doubleValue(); + return (new Float(floatVal)).doubleValue(); case BINARY: return convertIntToBytes(Float.floatToRawIntBits(floatVal), 4); default: @@ -275,7 +275,7 @@ static final Object convertDoubleToObject(double doubleVal, case DOUBLE: return doubleVal; case REAL: - return (Double.valueOf(doubleVal)).floatValue(); + return (new Double(doubleVal)).floatValue(); case INTEGER: return (int) doubleVal; case SMALLINT: // small and tinyint returned as short diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/FailOverInfo.java b/src/main/java/com/microsoft/sqlserver/jdbc/FailOverInfo.java index cdfe4fb83..0e905bc7d 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/FailOverInfo.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/FailOverInfo.java @@ -71,7 +71,7 @@ private void setupInfo(SQLServerConnection con) throws SQLServerException { instancePort = con.getInstancePort(failoverPartner, instanceValue); try { - portNumber = Integer.parseInt(instancePort); + portNumber = new Integer(instancePort); } catch (NumberFormatException e) { // Should not get here as the server should give a proper port number anyway. diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCSVFileRecord.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCSVFileRecord.java index cce49a416..4ff063dab 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCSVFileRecord.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCSVFileRecord.java @@ -23,6 +23,7 @@ import java.time.OffsetTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -574,7 +575,7 @@ public Object[] getRowData() throws SQLServerException { case Types.BIGINT: { BigDecimal bd = new BigDecimal(data[pair.getKey() - 1].trim()); try { - dataRow[pair.getKey() - 1] = bd.setScale(0, RoundingMode.DOWN).longValueExact(); + dataRow[pair.getKey() - 1] = bd.setScale(0, BigDecimal.ROUND_DOWN).longValueExact(); } catch (ArithmeticException ex) { String value = "'" + data[pair.getKey() - 1] + "'"; MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue")); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index e6ccfd9b2..730f13bf7 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -1418,7 +1418,7 @@ Connection connectInternal(Properties propsIn, sPropKey = SQLServerDriverIntProperty.STATEMENT_POOLING_CACHE_SIZE.toString(); if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) { try { - int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey)); + int n = new Integer(activeConnectionProperties.getProperty(sPropKey)); this.setStatementPoolingCacheSize(n); } catch (NumberFormatException e) { @@ -1555,7 +1555,7 @@ Connection connectInternal(Properties propsIn, try { String strPort = activeConnectionProperties.getProperty(sPropKey); if (null != strPort) { - nPort = Integer.parseInt(strPort); + nPort = new Integer(strPort); if ((nPort < 0) || (nPort > 65535)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidPortNumber")); @@ -1635,7 +1635,7 @@ else if (0 == requestedPacketSize) nLockTimeout = defaultLockTimeOut; // Wait forever if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) { try { - int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey)); + int n = new Integer(activeConnectionProperties.getProperty(sPropKey)); if (n >= defaultLockTimeOut) nLockTimeout = n; else { @@ -1656,7 +1656,7 @@ else if (0 == requestedPacketSize) queryTimeoutSeconds = defaultQueryTimeout; // Wait forever if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) { try { - int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey)); + int n = new Integer(activeConnectionProperties.getProperty(sPropKey)); if (n >= defaultQueryTimeout) { queryTimeoutSeconds = n; } @@ -1678,7 +1678,7 @@ else if (0 == requestedPacketSize) socketTimeoutMilliseconds = defaultSocketTimeout; // Wait forever if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) { try { - int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey)); + int n = new Integer(activeConnectionProperties.getProperty(sPropKey)); if (n >= defaultSocketTimeout) { socketTimeoutMilliseconds = n; } @@ -1698,7 +1698,7 @@ else if (0 == requestedPacketSize) sPropKey = SQLServerDriverIntProperty.SERVER_PREPARED_STATEMENT_DISCARD_THRESHOLD.toString(); if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) { try { - int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey)); + int n = new Integer(activeConnectionProperties.getProperty(sPropKey)); setServerPreparedStatementDiscardThreshold(n); } catch (NumberFormatException e) { @@ -2158,7 +2158,7 @@ ServerPortPlaceHolder primaryPermissionCheck(String primary, connectionlogger.fine(toString() + " SQL Server port returned by SQL Browser: " + instancePort); try { if (null != instancePort) { - primaryPortNumber = Integer.parseInt(instancePort); + primaryPortNumber = new Integer(instancePort); if ((primaryPortNumber < 0) || (primaryPortNumber > 65535)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidPortNumber")); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java index dddd46a88..49a6b25ba 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSource.java @@ -864,7 +864,7 @@ private void setIntProperty(Properties props, int propValue) { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "set" + propKey, propValue); - props.setProperty(propKey, Integer.valueOf(propValue).toString()); + props.setProperty(propKey, new Integer(propValue).toString()); loggerExternal.exiting(getClassNameLogging(), "set" + propKey); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSourceObjectFactory.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSourceObjectFactory.java index b2c11bb80..761eb26ae 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSourceObjectFactory.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataSourceObjectFactory.java @@ -8,7 +8,6 @@ package com.microsoft.sqlserver.jdbc; -import java.lang.reflect.InvocationTargetException; import java.util.Hashtable; import javax.naming.Context; @@ -36,7 +35,7 @@ public SQLServerDataSourceObjectFactory() { public Object getObjectInstance(Object ref, Name name, Context c, - Hashtable h) throws SQLServerException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + Hashtable h) throws SQLServerException { // Create a new instance of a DataSource class from the given reference. try { javax.naming.Reference r = (javax.naming.Reference) ref; @@ -60,7 +59,7 @@ public Object getObjectInstance(Object ref, // Create class instance and initialize using reference. Class dataSourceClass = Class.forName(className); - Object dataSourceClassInstance = dataSourceClass.getDeclaredConstructor().newInstance(); + Object dataSourceClassInstance = dataSourceClass.newInstance(); // If this class we created does not cast to SQLServerDataSource, then caller // passed in the wrong reference to our factory. diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java index 1063f903e..1dfeae276 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java @@ -632,7 +632,7 @@ private Properties parseAndMergeProperties(String Url, // put the user properties into the connect properties int nTimeout = DriverManager.getLoginTimeout(); if (nTimeout > 0) { - connectProperties.put(SQLServerDriverIntProperty.LOGIN_TIMEOUT.toString(), Integer.valueOf(nTimeout).toString()); + connectProperties.put(SQLServerDriverIntProperty.LOGIN_TIMEOUT.toString(), new Integer(nTimeout).toString()); } // Merge connectProperties (from URL) and supplied properties from user. diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSQLXML.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSQLXML.java index cc1ed87de..7e8881d8b 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSQLXML.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSQLXML.java @@ -23,8 +23,6 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; @@ -50,6 +48,7 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; /** * SQLServerSQLXML represents an XML object and implements a java.sql.SQLXML. @@ -406,14 +405,12 @@ private DOMSource getDOMSource() throws SQLException { private SAXSource getSAXSource() throws SQLException { try { InputSource src = new InputSource(contents); - SAXParserFactory factory=SAXParserFactory.newInstance(); - SAXParser parser=factory.newSAXParser(); - XMLReader reader = parser.getXMLReader(); + XMLReader reader = XMLReaderFactory.createXMLReader(); SAXSource saxSource = new SAXSource(reader, src); return saxSource; } - catch (SAXException | ParserConfigurationException e) { + catch (SAXException e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_failedToParseXML")); Object[] msgArgs = {e.toString()}; SQLServerException.makeFromDriverError(con, null, form.format(msgArgs), null, true); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SqlVariant.java b/src/main/java/com/microsoft/sqlserver/jdbc/SqlVariant.java index 868db7102..2d4c13436 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SqlVariant.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SqlVariant.java @@ -62,7 +62,7 @@ static sqlVariantProbBytes valueOf(int intValue) { if (!(0 <= intValue && intValue < valuesTypes.length) || null == (tdsType = valuesTypes[intValue])) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unknownSSType")); - Object[] msgArgs = {Integer.valueOf(intValue)}; + Object[] msgArgs = {new Integer(intValue)}; throw new IllegalArgumentException(form.format(msgArgs)); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java index 584cfd681..e0ea30378 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java @@ -2208,7 +2208,7 @@ void execute(DTV dtv, if (null != bigDecimalValue) { Integer inScale = dtv.getScale(); if (null != inScale && inScale != bigDecimalValue.scale()) - bigDecimalValue = bigDecimalValue.setScale(inScale, RoundingMode.DOWN); + bigDecimalValue = bigDecimalValue.setScale(inScale, BigDecimal.ROUND_DOWN); } dtv.setValue(bigDecimalValue, JavaType.BIGDECIMAL); From 0b410f0cf6e63a5e4f1868348c8f47658b07e75c Mon Sep 17 00:00:00 2001 From: Jamie Magee Date: Fri, 22 Sep 2017 11:56:33 +0000 Subject: [PATCH 09/68] Replace manual array copy Replace manual array copying with System.arraycopy(). --- src/main/java/com/microsoft/sqlserver/jdbc/DDC.java | 4 +--- .../sqlserver/jdbc/SQLServerPreparedStatement.java | 6 ++---- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java index 6bf3af9e6..77891c37b 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java @@ -439,9 +439,7 @@ private static byte[] convertToBytes(BigDecimal value, } } int offset = numBytes - unscaledBytes.length; - for (int i = offset; i < numBytes; ++i) { - ret[i] = unscaledBytes[i - offset]; - } + System.arraycopy(unscaledBytes, offset - offset, ret, offset, numBytes - offset); return ret; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 1ba3c62e8..2437a82d0 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2503,8 +2503,7 @@ public long[] executeLargeBatch() throws SQLServerException, BatchUpdateExceptio updateCounts = new long[batchCommand.updateCounts.length]; - for (int i = 0; i < batchCommand.updateCounts.length; ++i) - updateCounts[i] = batchCommand.updateCounts[i]; + System.arraycopy(batchCommand.updateCounts, 0, updateCounts, 0, batchCommand.updateCounts.length); // Transform the SQLException into a BatchUpdateException with the update counts. if (null != batchCommand.batchException) { @@ -2571,8 +2570,7 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th // Fill in the parameter values for this batch Parameter paramValues[] = batchParamValues.get(numBatchesPrepared); assert paramValues.length == batchParam.length; - for (int i = 0; i < paramValues.length; i++) - batchParam[i] = paramValues[i]; + System.arraycopy(paramValues, 0, batchParam, 0, paramValues.length); boolean hasExistingTypeDefinitions = preparedTypeDefinitions != null; boolean hasNewTypeDefinitions = buildPreparedStrings(batchParam, false); From 16bd589944ae1589e42fbdece4efc6b04b715c91 Mon Sep 17 00:00:00 2001 From: Jamie Magee Date: Fri, 22 Sep 2017 12:00:00 +0000 Subject: [PATCH 10/68] Remove redundant String.toString() Calling toString() on a String object is redundant --- src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java | 2 +- .../java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java | 2 +- .../com/microsoft/sqlserver/jdbc/SQLServerConnection.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index 4369d3c00..db19dce37 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -4828,7 +4828,7 @@ private void writeInternalTVPRowValues(JDBCType jdbcType, else { if (isSqlVariant) { writeTVPSqlVariantHeader(10, TDSType.FLOAT8.byteValue(), (byte) 0); - writeDouble(Double.valueOf(currentColumnStringValue.toString())); + writeDouble(Double.valueOf(currentColumnStringValue)); break; } writeByte((byte) 8); // len of data bytes diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java index 14e4338b3..a383e1946 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java @@ -1521,7 +1521,7 @@ private String createInsertBulkCommand(TDSWriter tdsWriter) throws SQLServerExce if (it.hasNext()) { bulkCmd.append(" with ("); while (it.hasNext()) { - bulkCmd.append(it.next().toString()); + bulkCmd.append(it.next()); if (it.hasNext()) { bulkCmd.append(", "); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 730f13bf7..a8397b605 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -1717,7 +1717,7 @@ else if (0 == requestedPacketSize) sPropKey = SQLServerDriverStringProperty.SSL_PROTOCOL.toString(); sPropValue = activeConnectionProperties.getProperty(sPropKey); if (null == sPropValue) { - sPropValue = SQLServerDriverStringProperty.SSL_PROTOCOL.getDefaultValue().toString(); + sPropValue = SQLServerDriverStringProperty.SSL_PROTOCOL.getDefaultValue(); activeConnectionProperties.setProperty(sPropKey, sPropValue); } else { @@ -5430,7 +5430,7 @@ String getInstancePort(String server, browserResult = new String(receiveBuffer, 3, receiveBuffer.length - 3); if (connectionlogger.isLoggable(Level.FINER)) connectionlogger.fine( - toString() + " Received SSRP UDP response from IP address: " + udpResponse.getAddress().getHostAddress().toString()); + toString() + " Received SSRP UDP response from IP address: " + udpResponse.getAddress().getHostAddress()); } catch (IOException ioException) { // Warn and retry From d94cccc75bab0fa6fd63af147e3f5bb8d80787a6 Mon Sep 17 00:00:00 2001 From: Jamie Magee Date: Fri, 22 Sep 2017 12:16:52 +0000 Subject: [PATCH 11/68] Replace bare literals Replace bare literals with magic constants. For example: `cal.set(1, 1, 577738, 0, 0, 0);` becomes `cal.set(1, Calendar.FEBRUARY, 577738, 0, 0, 0);` --- src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java | 2 +- .../microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java | 2 +- .../microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index 4369d3c00..c0ba49d71 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -498,7 +498,7 @@ class GregorianChange { GregorianCalendar cal = new GregorianCalendar(Locale.US); cal.clear(); - cal.set(1, 1, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582) + cal.set(1, Calendar.FEBRUARY, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582) if (cal.get(Calendar.DAY_OF_MONTH) == 15) { // If the date calculation is correct(the above bug is fixed), // post the default gregorian cut over date, the pure gregorian date diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java index ec44c1834..ea9ff510f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java @@ -75,7 +75,7 @@ static Object getTemporalObjectFromCSVWithFormatter(String valueStrUntrimmed, return ts; case java.sql.Types.TIME: // Time is returned as Timestamp to preserve nano seconds. - cal.set(connection.baseYear(), 00, 01); + cal.set(connection.baseYear(), Calendar.JANUARY, 01); ts = new java.sql.Timestamp(cal.getTimeInMillis()); ts.setNanos(taNano); return new java.sql.Timestamp(ts.getTime()); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java index 601e06274..425d741bf 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java @@ -788,7 +788,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + return ParameterMetaData.parameterModeUnknown; } } @@ -908,7 +908,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + return ParameterMetaData.parameterNoNulls; } } From 4224a6fb6eaafa2f809d073af384c8ba13a60b86 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Fri, 22 Sep 2017 09:52:05 -0700 Subject: [PATCH 12/68] release process PR --- CHANGELOG.md | 16 ++++++++++++++++ pom.xml | 2 +- .../microsoft/sqlserver/jdbc/SQLJdbcVersion.java | 2 +- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 287ca0c2a..409897623 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,22 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## [6.3.3] Preview Release +### Added +- Added connection properties for specifying custom TrustManager [#74] (https://github.com/Microsoft/mssql-jdbc/pull/74) + +### Fixed Issues +- Fixed exception thrown by getters on null columns [#488] (https://github.com/Microsoft/mssql-jdbc/pull/488) +- Fixed issue with DatabaseMetaData#getImportedKeys() returns wrong value for DELETE_RULE [#490] (https://github.com/Microsoft/mssql-jdbc/pull/490) +- Fixed issue with ActivityCorrelator causing a classloader leak [#465] (https://github.com/Microsoft/mssql-jdbc/pull/465) + +### Changed +- Removed explicit extends Object [#469] (https://github.com/Microsoft/mssql-jdbc/pull/469) +- Removed redundant if/else statements [#470] (https://github.com/Microsoft/mssql-jdbc/pull/470) +- Removed unnecessary return statements [#471] (https://github.com/Microsoft/mssql-jdbc/pull/471) +- Simplified overly complex boolean expressions [#472] (https://github.com/Microsoft/mssql-jdbc/pull/472) +- Replaced explicit types with <> (the diamond operator) [#420] (https://github.com/Microsoft/mssql-jdbc/pull/420) + ## [6.3.2] Preview Release ### Added - Added new connection property: sslProtocol [#422](https://github.com/Microsoft/mssql-jdbc/pull/422) diff --git a/pom.xml b/pom.xml index 1851a2f89..54c63a5cf 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.3-SNAPSHOT + 6.3.3-preview jar diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java index e7f5bccf7..9c9f7b691 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java @@ -11,6 +11,6 @@ final class SQLJdbcVersion { static final int major = 6; static final int minor = 3; - static final int patch = 2; + static final int patch = 3; static final int build = 0; } From 139ea00ff0c300b3ec2a531422da6d0a61752d12 Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Fri, 22 Sep 2017 10:28:15 -0700 Subject: [PATCH 13/68] Revert "Remove redundant if/else statements" --- ...umnEncryptionCertificateStoreProvider.java | 7 ++- .../jdbc/SQLServerDatabaseMetaData.java | 46 +++++++++++++------ .../jdbc/SQLServerParameterMetaData.java | 7 ++- .../sqlserver/jdbc/SQLServerResultSet.java | 6 ++- .../sqlserver/jdbc/StreamColInfo.java | 3 +- .../sqlserver/jdbc/StreamColumns.java | 3 +- .../microsoft/sqlserver/jdbc/StreamError.java | 3 +- .../microsoft/sqlserver/jdbc/StreamInfo.java | 3 +- .../sqlserver/jdbc/StreamLoginAck.java | 3 +- .../sqlserver/jdbc/StreamRetStatus.java | 3 +- .../sqlserver/jdbc/StreamRetValue.java | 3 +- .../microsoft/sqlserver/jdbc/StreamSSPI.java | 3 +- .../sqlserver/jdbc/StreamTabName.java | 3 +- .../com/microsoft/sqlserver/jdbc/Util.java | 5 +- 14 files changed, 70 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java index 4a38df69e..91a473b73 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerColumnEncryptionCertificateStoreProvider.java @@ -45,7 +45,12 @@ public final class SQLServerColumnEncryptionCertificateStoreProvider extends SQL static final String myCertificateStore = "My"; static { - isWindows = System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows"); + if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) { + isWindows = true; + } + else { + isWindows = false; + } } private Path keyStoreDirectoryPath = null; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java index 34bafaea7..516a4d590 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java @@ -1968,7 +1968,10 @@ else if (name.equals(SQLServerDriverIntProperty.PORT_NUMBER.toString())) { case ResultSet.TYPE_SCROLL_INSENSITIVE: // case SQLServerResultSet.TYPE_SS_SCROLL_STATIC: sensitive synonym case SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY: - return ResultSet.CONCUR_READ_ONLY == concurrency; + if (ResultSet.CONCUR_READ_ONLY == concurrency) + return true; + else + return false; } // per spec if we do not know we do not support. return false; @@ -1977,48 +1980,60 @@ else if (name.equals(SQLServerDriverIntProperty.PORT_NUMBER.toString())) { /* L0 */ public boolean ownUpdatesAreVisible(int type) throws SQLServerException { checkClosed(); checkResultType(type); - return type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type + if (type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type || SQLServerResultSet.TYPE_SCROLL_SENSITIVE == type || SQLServerResultSet.TYPE_SS_SCROLL_KEYSET == type - || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type; + || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type) + return true; + return false; } /* L0 */ public boolean ownDeletesAreVisible(int type) throws SQLServerException { checkClosed(); checkResultType(type); - return type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type + if (type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type || SQLServerResultSet.TYPE_SCROLL_SENSITIVE == type || SQLServerResultSet.TYPE_SS_SCROLL_KEYSET == type - || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type; + || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type) + return true; + return false; } /* L0 */ public boolean ownInsertsAreVisible(int type) throws SQLServerException { checkClosed(); checkResultType(type); - return type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type + if (type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type || SQLServerResultSet.TYPE_SCROLL_SENSITIVE == type || SQLServerResultSet.TYPE_SS_SCROLL_KEYSET == type - || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type; + || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type) + return true; + return false; } /* L0 */ public boolean othersUpdatesAreVisible(int type) throws SQLServerException { checkClosed(); checkResultType(type); - return type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type + if (type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type || SQLServerResultSet.TYPE_SCROLL_SENSITIVE == type || SQLServerResultSet.TYPE_SS_SCROLL_KEYSET == type - || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type; + || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type) + return true; + return false; } /* L0 */ public boolean othersDeletesAreVisible(int type) throws SQLServerException { checkClosed(); checkResultType(type); - return type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type + if (type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type || SQLServerResultSet.TYPE_SCROLL_SENSITIVE == type || SQLServerResultSet.TYPE_SS_SCROLL_KEYSET == type - || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type; + || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type) + return true; + return false; } /* L0 */ public boolean othersInsertsAreVisible(int type) throws SQLServerException { checkClosed(); checkResultType(type); - return type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type - || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type; + if (type == SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC || SQLServerResultSet.TYPE_FORWARD_ONLY == type + || SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == type) + return true; + return false; } /* L0 */ public boolean updatesAreDetected(int type) throws SQLServerException { @@ -2030,7 +2045,10 @@ else if (name.equals(SQLServerDriverIntProperty.PORT_NUMBER.toString())) { /* L0 */ public boolean deletesAreDetected(int type) throws SQLServerException { checkClosed(); checkResultType(type); - return SQLServerResultSet.TYPE_SS_SCROLL_KEYSET == type; + if (SQLServerResultSet.TYPE_SS_SCROLL_KEYSET == type) + return true; + else + return false; } // Check the result types to make sure the user does not pass a bad value. diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java index 601e06274..1d11e61af 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java @@ -581,7 +581,12 @@ private void checkClosed() throws SQLServerException { rsProcedureMeta = s.executeQueryInternal("exec sp_sproc_columns " + sProc + ", @ODBCVer=3"); // if rsProcedureMeta has next row, it means the stored procedure is found - procedureIsFound = rsProcedureMeta.next(); + if (rsProcedureMeta.next()) { + procedureIsFound = true; + } + else { + procedureIsFound = false; + } rsProcedureMeta.beforeFirst(); // Sixth is DATA_TYPE diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java index 8c58a8c94..e937b27c3 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java @@ -6280,7 +6280,8 @@ boolean onRow(TDSReader tdsReader) throws SQLServerException { // Consume the ROW token, leaving tdsReader at the start of // this row's column values. - assert TDS.TDS_ROW == tdsReader.readUnsignedByte(); + if (TDS.TDS_ROW != tdsReader.readUnsignedByte()) + assert false; fetchBufferCurrentRowType = RowType.ROW; return false; } @@ -6290,7 +6291,8 @@ boolean onNBCRow(TDSReader tdsReader) throws SQLServerException { // Consume the NBCROW token, leaving tdsReader at the start of // nullbitmap. - assert TDS.TDS_NBCROW == tdsReader.readUnsignedByte(); + if (TDS.TDS_NBCROW != tdsReader.readUnsignedByte()) + assert false; fetchBufferCurrentRowType = RowType.NBCROW; return false; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamColInfo.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamColInfo.java index 366307b34..e0d7eaeb5 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamColInfo.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamColInfo.java @@ -21,7 +21,8 @@ final class StreamColInfo extends StreamPacket { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_COLINFO == tdsReader.readUnsignedByte() : "Not a COLINFO token"; + if (TDS.TDS_COLINFO != tdsReader.readUnsignedByte()) + assert false : "Not a COLINFO token"; this.tdsReader = tdsReader; int tokenLength = tdsReader.readUnsignedShort(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamColumns.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamColumns.java index 0553cb47b..3128fb318 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamColumns.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamColumns.java @@ -163,7 +163,8 @@ CryptoMetadata readCryptoMetadata(TDSReader tdsReader) throws SQLServerException * @throws SQLServerException */ void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_COLMETADATA == tdsReader.readUnsignedByte(); + if (TDS.TDS_COLMETADATA != tdsReader.readUnsignedByte()) + assert false; int nTotColumns = tdsReader.readUnsignedShort(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamError.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamError.java index 62c0ebdd3..c7d2418db 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamError.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamError.java @@ -47,7 +47,8 @@ final int getErrorSeverity() { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_ERR == tdsReader.readUnsignedByte(); + if (TDS.TDS_ERR != tdsReader.readUnsignedByte()) + assert false; setContentsFromTDS(tdsReader); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamInfo.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamInfo.java index fe55ae1f9..ef32b463f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamInfo.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamInfo.java @@ -16,7 +16,8 @@ final class StreamInfo extends StreamPacket { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_MSG == tdsReader.readUnsignedByte(); + if (TDS.TDS_MSG != tdsReader.readUnsignedByte()) + assert false; msg.setContentsFromTDS(tdsReader); } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamLoginAck.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamLoginAck.java index 608b452d2..1abe2a133 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamLoginAck.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamLoginAck.java @@ -22,7 +22,8 @@ final class StreamLoginAck extends StreamPacket { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_LOGIN_ACK == tdsReader.readUnsignedByte(); + if (TDS.TDS_LOGIN_ACK != tdsReader.readUnsignedByte()) + assert false; tdsReader.readUnsignedShort(); // length of this token stream tdsReader.readUnsignedByte(); // SQL version accepted by the server tdsVersion = tdsReader.readIntBigEndian(); // TDS version accepted by the server diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetStatus.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetStatus.java index 54ab19249..51b44cde0 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetStatus.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetStatus.java @@ -25,7 +25,8 @@ final int getStatus() { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_RET_STAT == tdsReader.readUnsignedByte(); + if (TDS.TDS_RET_STAT != tdsReader.readUnsignedByte()) + assert false; status = tdsReader.readInt(); } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetValue.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetValue.java index 35d3b17fd..c2947dd56 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetValue.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamRetValue.java @@ -33,7 +33,8 @@ final int getOrdinalOrLength() { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_RETURN_VALUE == tdsReader.readUnsignedByte(); + if (TDS.TDS_RETURN_VALUE != tdsReader.readUnsignedByte()) + assert false; ordinalOrLength = tdsReader.readUnsignedShort(); paramName = tdsReader.readUnicodeString(tdsReader.readUnsignedByte()); status = tdsReader.readUnsignedByte(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamSSPI.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamSSPI.java index fca3e0cd0..1a9b4d346 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamSSPI.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamSSPI.java @@ -21,7 +21,8 @@ final class StreamSSPI extends StreamPacket { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_SSPI == tdsReader.readUnsignedByte(); + if (TDS.TDS_SSPI != tdsReader.readUnsignedByte()) + assert false; int blobLength = tdsReader.readUnsignedShort(); sspiBlob = new byte[blobLength]; tdsReader.readBytes(sspiBlob, 0, blobLength); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java index d728785b6..31acff46f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java @@ -22,7 +22,8 @@ final class StreamTabName extends StreamPacket { } void setFromTDS(TDSReader tdsReader) throws SQLServerException { - assert TDS.TDS_TABNAME == tdsReader.readUnsignedByte() : "Not a TABNAME token"; + if (TDS.TDS_TABNAME != tdsReader.readUnsignedByte()) + assert false : "Not a TABNAME token"; this.tdsReader = tdsReader; int tokenLength = tdsReader.readUnsignedShort(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java index eb585e540..db10ebce1 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java @@ -790,7 +790,10 @@ static final String readGUID(byte[] inputGUID) throws SQLServerException { static boolean IsActivityTraceOn() { LogManager lm = LogManager.getLogManager(); String activityTrace = lm.getProperty(ActivityIdTraceProperty); - return "on".equalsIgnoreCase(activityTrace); + if ("on".equalsIgnoreCase(activityTrace)) + return true; + else + return false; } /** From 270603d4e03e50162617240c79802815f3797882 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Fri, 22 Sep 2017 10:55:01 -0700 Subject: [PATCH 14/68] remove PR 470 from changelist, and modify the readme file --- CHANGELOG.md | 1 - README.md | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 409897623..f8feeda58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,6 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) ### Changed - Removed explicit extends Object [#469] (https://github.com/Microsoft/mssql-jdbc/pull/469) -- Removed redundant if/else statements [#470] (https://github.com/Microsoft/mssql-jdbc/pull/470) - Removed unnecessary return statements [#471] (https://github.com/Microsoft/mssql-jdbc/pull/471) - Simplified overly complex boolean expressions [#472] (https://github.com/Microsoft/mssql-jdbc/pull/472) - Replaced explicit types with <> (the diamond operator) [#420] (https://github.com/Microsoft/mssql-jdbc/pull/420) diff --git a/README.md b/README.md index 5fd1154ac..5bb33d3bd 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ To get the latest preview version of the driver, add the following to your POM f com.microsoft.sqlserver mssql-jdbc - 6.3.2.jre8-preview + 6.3.3.jre8-preview ``` @@ -120,7 +120,7 @@ Projects that require either of the two features need to explicitly declare the com.microsoft.sqlserver mssql-jdbc - 6.3.2.jre8-preview + 6.3.3.jre8-preview compile From 7406b4772929ac71eff22be44c59caa4ead72c9f Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Fri, 22 Sep 2017 11:01:07 -0700 Subject: [PATCH 15/68] remove preview from pom --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 54c63a5cf..160fdabd0 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.3-preview + 6.3.3 jar From d1cb96376bd7cecd74067e76c15c1208f831bfd2 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Fri, 22 Sep 2017 11:15:26 -0700 Subject: [PATCH 16/68] make urls work --- CHANGELOG.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f8feeda58..9ebc0ce1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,18 +5,18 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) ## [6.3.3] Preview Release ### Added -- Added connection properties for specifying custom TrustManager [#74] (https://github.com/Microsoft/mssql-jdbc/pull/74) +- Added connection properties for specifying custom TrustManager [#74](https://github.com/Microsoft/mssql-jdbc/pull/74) ### Fixed Issues -- Fixed exception thrown by getters on null columns [#488] (https://github.com/Microsoft/mssql-jdbc/pull/488) -- Fixed issue with DatabaseMetaData#getImportedKeys() returns wrong value for DELETE_RULE [#490] (https://github.com/Microsoft/mssql-jdbc/pull/490) -- Fixed issue with ActivityCorrelator causing a classloader leak [#465] (https://github.com/Microsoft/mssql-jdbc/pull/465) +- Fixed exception thrown by getters on null columns [#488](https://github.com/Microsoft/mssql-jdbc/pull/488) +- Fixed issue with DatabaseMetaData#getImportedKeys() returns wrong value for DELETE_RULE [#490](https://github.com/Microsoft/mssql-jdbc/pull/490) +- Fixed issue with ActivityCorrelator causing a classloader leak [#465](https://github.com/Microsoft/mssql-jdbc/pull/465) ### Changed -- Removed explicit extends Object [#469] (https://github.com/Microsoft/mssql-jdbc/pull/469) -- Removed unnecessary return statements [#471] (https://github.com/Microsoft/mssql-jdbc/pull/471) -- Simplified overly complex boolean expressions [#472] (https://github.com/Microsoft/mssql-jdbc/pull/472) -- Replaced explicit types with <> (the diamond operator) [#420] (https://github.com/Microsoft/mssql-jdbc/pull/420) +- Removed explicit extends Object [#469](https://github.com/Microsoft/mssql-jdbc/pull/469) +- Removed unnecessary return statements [#471](https://github.com/Microsoft/mssql-jdbc/pull/471) +- Simplified overly complex boolean expressions [#472](https://github.com/Microsoft/mssql-jdbc/pull/472) +- Replaced explicit types with <> (the diamond operator) [#420](https://github.com/Microsoft/mssql-jdbc/pull/420) ## [6.3.2] Preview Release ### Added From f8696c54a1e138cdd05196e6b5394aca6a5396ee Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Mon, 25 Sep 2017 10:49:43 -0700 Subject: [PATCH 17/68] remove developer name from POM file --- pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pom.xml b/pom.xml index 160fdabd0..968bfada3 100644 --- a/pom.xml +++ b/pom.xml @@ -29,8 +29,6 @@ - Andrea Lam - andrela@microsoft.com Microsoft http://www.microsoft.com From 6f262f871062496bb76fdd70624133bb9b987b93 Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Mon, 25 Sep 2017 15:18:21 -0700 Subject: [PATCH 18/68] cleanup tables after test --- .../jdbc/unit/statement/StatementTest.java | 443 +++++++----------- 1 file changed, 174 insertions(+), 269 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java index 715f1c457..ba033d2aa 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java @@ -1172,10 +1172,26 @@ public void testLargeMaxRowsJDBC42() throws Exception { } } + @AfterEach + public void terminate() throws Exception { + Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); + try { + Utils.dropTableIfExists(table1Name, stmt); + Utils.dropTableIfExists(table2Name, stmt); + } + catch (SQLException e) { + } + stmt.close(); + con.close(); + } + } @Nested public class TCStatementCallable { + String name = RandomUtil.getIdentifier("p1"); + String procName = AbstractSQLGenerator.escapeIdentifier(name); /** * Tests CallableStatementMethods on jdbc41 @@ -1187,41 +1203,19 @@ public void testJdbc41CallableStatementMethods() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Prepare database setup - String name = RandomUtil.getIdentifier("p1"); - String procName = AbstractSQLGenerator.escapeIdentifier(name); try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - String query = "create procedure " + procName - + " @col1Value varchar(512) OUTPUT," - + " @col2Value int OUTPUT," - + " @col3Value float OUTPUT," - + " @col4Value decimal(10,5) OUTPUT," - + " @col5Value uniqueidentifier OUTPUT," - + " @col6Value xml OUTPUT," - + " @col7Value varbinary(max) OUTPUT," - + " @col8Value text OUTPUT," - + " @col9Value ntext OUTPUT," - + " @col10Value varbinary(max) OUTPUT," - + " @col11Value date OUTPUT," - + " @col12Value time OUTPUT," - + " @col13Value datetime2 OUTPUT," - + " @col14Value datetimeoffset OUTPUT" - + " AS BEGIN " - + " SET @col1Value = 'hello'" - + " SET @col2Value = 1" - + " SET @col3Value = 2.0" - + " SET @col4Value = 123.45" - + " SET @col5Value = '6F9619FF-8B86-D011-B42D-00C04FC964FF'" - + " SET @col6Value = ''" - + " SET @col7Value = 0x63C34D6BCAD555EB64BF7E848D02C376" - + " SET @col8Value = 'text'" - + " SET @col9Value = 'ntext'" - + " SET @col10Value = 0x63C34D6BCAD555EB64BF7E848D02C376" - + " SET @col11Value = '2017-05-19'" - + " SET @col12Value = '10:47:15.1234567'" - + " SET @col13Value = '2017-05-19T10:47:15.1234567'" - + " SET @col14Value = '2017-05-19T10:47:15.1234567+02:00'" - + " END"; + String query = "create procedure " + procName + " @col1Value varchar(512) OUTPUT," + " @col2Value int OUTPUT," + + " @col3Value float OUTPUT," + " @col4Value decimal(10,5) OUTPUT," + " @col5Value uniqueidentifier OUTPUT," + + " @col6Value xml OUTPUT," + " @col7Value varbinary(max) OUTPUT," + " @col8Value text OUTPUT," + " @col9Value ntext OUTPUT," + + " @col10Value varbinary(max) OUTPUT," + " @col11Value date OUTPUT," + " @col12Value time OUTPUT," + + " @col13Value datetime2 OUTPUT," + " @col14Value datetimeoffset OUTPUT" + " AS BEGIN " + " SET @col1Value = 'hello'" + + " SET @col2Value = 1" + " SET @col3Value = 2.0" + " SET @col4Value = 123.45" + + " SET @col5Value = '6F9619FF-8B86-D011-B42D-00C04FC964FF'" + " SET @col6Value = ''" + + " SET @col7Value = 0x63C34D6BCAD555EB64BF7E848D02C376" + " SET @col8Value = 'text'" + " SET @col9Value = 'ntext'" + + " SET @col10Value = 0x63C34D6BCAD555EB64BF7E848D02C376" + " SET @col11Value = '2017-05-19'" + + " SET @col12Value = '10:47:15.1234567'" + " SET @col13Value = '2017-05-19T10:47:15.1234567'" + + " SET @col14Value = '2017-05-19T10:47:15.1234567+02:00'" + " END"; stmt.execute(query); // Test JDBC 4.1 methods for CallableStatement @@ -1244,7 +1238,7 @@ public void testJdbc41CallableStatementMethods() throws Exception { assertEquals("hello", cstmt.getObject(1, String.class)); assertEquals("hello", cstmt.getObject("col1Value", String.class)); - + assertEquals(Integer.valueOf(1), cstmt.getObject(2, Integer.class)); assertEquals(Integer.valueOf(1), cstmt.getObject("col2Value", Integer.class)); @@ -1256,7 +1250,7 @@ public void testJdbc41CallableStatementMethods() throws Exception { // BigDecimal#equals considers the number of decimal places assertEquals(0, cstmt.getObject(4, BigDecimal.class).compareTo(new BigDecimal("123.45"))); assertEquals(0, cstmt.getObject("col4Value", BigDecimal.class).compareTo(new BigDecimal("123.45"))); - + assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), cstmt.getObject(5, UUID.class)); assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), cstmt.getObject("col5Value", UUID.class)); @@ -1264,16 +1258,18 @@ public void testJdbc41CallableStatementMethods() throws Exception { sqlXml = cstmt.getObject(6, SQLXML.class); try { assertEquals("", sqlXml.getString()); - } finally { + } + finally { sqlXml.free(); } Blob blob; blob = cstmt.getObject(7, Blob.class); try { - assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, - blob.getBytes(1, 16)); - } finally { + assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, + 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, blob.getBytes(1, 16)); + } + finally { blob.free(); } @@ -1281,7 +1277,8 @@ public void testJdbc41CallableStatementMethods() throws Exception { clob = cstmt.getObject(8, Clob.class); try { assertEquals("text", clob.getSubString(1, 4)); - } finally { + } + finally { clob.free(); } @@ -1289,12 +1286,13 @@ public void testJdbc41CallableStatementMethods() throws Exception { nclob = cstmt.getObject(9, NClob.class); try { assertEquals("ntext", nclob.getSubString(1, 5)); - } finally { + } + finally { nclob.free(); } - assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, - cstmt.getObject(10, byte[].class)); + assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, + (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, cstmt.getObject(10, byte[].class)); assertEquals(java.sql.Date.valueOf("2017-05-19"), cstmt.getObject(11, java.sql.Date.class)); assertEquals(java.sql.Date.valueOf("2017-05-19"), cstmt.getObject("col11Value", java.sql.Date.class)); @@ -1307,18 +1305,30 @@ public void testJdbc41CallableStatementMethods() throws Exception { assertEquals("2017-05-19 10:47:15.1234567 +02:00", cstmt.getObject(14, microsoft.sql.DateTimeOffset.class).toString()); assertEquals("2017-05-19 10:47:15.1234567 +02:00", cstmt.getObject("col14Value", microsoft.sql.DateTimeOffset.class).toString()); - } finally { - Utils.dropProcedureIfExists(procName, stmt); } } } + + @AfterEach + public void terminate() throws Exception { + Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); + try { + Utils.dropProcedureIfExists(procName, stmt); + } + catch (SQLException e) { + } + stmt.close(); + con.close(); + } + } @Nested public class TCStatementParam { String tableNameTemp = RandomUtil.getIdentifier("TCStatementParam"); private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); - String procNameTemp = RandomUtil.getIdentifier("p1"); + String procNameTemp = "TCStatementParam"; private final String procName = AbstractSQLGenerator.escapeIdentifier(procNameTemp); /** @@ -1339,9 +1349,8 @@ public void testStatementOutParamGetsTwice() throws Exception { log.fine("testStatementOutParamGetsTwice threw: " + e.getMessage()); } - Utils.dropProcedureIfExists("sp_ouputP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); ResultSet rs = stmt.getResultSet(); if (rs != null) { @@ -1351,7 +1360,7 @@ public void testStatementOutParamGetsTwice() throws Exception { else { assertEquals(stmt.isClosed(), false, "testStatementOutParamGetsTwice: statement should be open since no resultset."); } - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputP] (?,?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1372,7 +1381,6 @@ public void testStatementOutParamGetsTwice() throws Exception { else { assertEquals((stmt).isClosed(), false, "testStatementOutParamGetsTwice: statement should be open since no resultset."); } - Utils.dropProcedureIfExists("sp_ouputP", stmt); } @Test @@ -1380,11 +1388,10 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - Utils.dropProcedureIfExists("sp_ouputMP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputMP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT, @p4_smallint smallint OUTPUT, @p5_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint, @p5_smallint_out=@p4_smallint RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT, @p4_smallint smallint OUTPUT, @p5_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint, @p5_smallint_out=@p4_smallint RETURN @p2_smallint + 1"); - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputMP] (?,?, ?, ?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?, ?, ?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1401,8 +1408,6 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { assertEquals(cstmt.getInt(3), 34, "Wrong value"); assertEquals(cstmt.getInt(5), 24, "Wrong value"); assertEquals(cstmt.getInt(1), 35, "Wrong value"); - - Utils.dropProcedureIfExists("sp_ouputMP", stmt); } /** @@ -1415,11 +1420,10 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - Utils.dropProcedureIfExists("sp_ouputP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p3_smallint_out +1 RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p3_smallint_out +1 RETURN @p2_smallint + 1"); - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputP] (?,?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("1"), Types.SMALLINT); cstmt.setObject(3, Short.valueOf("100"), Types.SMALLINT); @@ -1432,8 +1436,6 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { cstmt.execute(); assertEquals(cstmt.getInt(1), 11, "Wrong value"); assertEquals(cstmt.getInt(3), 101, "Wrong value"); - - Utils.dropProcedureIfExists("sp_ouputP", stmt); } /** @@ -1447,18 +1449,6 @@ public void testResultSetParams() throws Exception { Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1473,19 +1463,6 @@ public void testResultSetParams() throws Exception { rs.next(); assertEquals(rs.getString(2), "hello", "Wrong value"); assertEquals(cstmt.getString(2), "hi", "Wrong value"); - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** @@ -1495,25 +1472,10 @@ public void testResultSetParams() throws Exception { */ @Test public void testResultSetNullParams() throws Exception { - String temp = RandomUtil.getIdentifier("RetestResultSetNullParams"); - String tableName = AbstractSQLGenerator.escapeIdentifier(temp); - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1531,19 +1493,6 @@ public void testResultSetNullParams() throws Exception { throw ex; } ; - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** @@ -1555,12 +1504,7 @@ public void testFailedToResumeTransaction() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; + stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0)"); stmt.executeUpdate("Insert into " + tableName + " values(1)"); @@ -1581,12 +1525,6 @@ public void testFailedToResumeTransaction() throws Exception { } catch (SQLException ex) { } - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; conn.close(); } @@ -1600,18 +1538,6 @@ public void testResultSetErrors() throws Exception { Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1631,45 +1557,20 @@ public void testResultSetErrors() throws Exception { ; assertEquals(null, cstmt.getString(2), "Wrong value"); - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** * Verify proper handling of row errors in ResultSets. */ @Test - @Disabled - //TODO: We are commenting this out due to random AppVeyor failures. We will investigate later. + @Disabled + // TODO: We are commenting this out due to random AppVeyor failures. We will investigate later. public void testRowError() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); // Set up everything Statement stmt = conn.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); stmt.executeUpdate("insert into " + tableName + " values(0)"); @@ -1757,21 +1658,22 @@ public void testRowError() throws Exception { testConn2.close(); testConn1.close(); } + stmt.close(); + conn.close(); + } + @AfterEach + public void terminate() throws Exception { + Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); try { Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { Utils.dropProcedureIfExists(procName, stmt); } - catch (Exception ex) { + catch (SQLException e) { } - ; stmt.close(); - conn.close(); + con.close(); } } @@ -1790,11 +1692,6 @@ private Connection createConnectionAndPopulateData() throws Exception { con = ds.getConnection(); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } stmt.executeUpdate("CREATE TABLE " + tableName + "(col1_int int PRIMARY KEY IDENTITY(1,1), col2_varchar varchar(200), col3_varchar varchar(20) SPARSE NULL, col4_smallint smallint SPARSE NULL, col5_xml XML COLUMN_SET FOR ALL_SPARSE_COLUMNS, col6_nvarcharMax NVARCHAR(MAX), col7_varcharMax VARCHAR(MAX))"); @@ -1804,20 +1701,17 @@ private Connection createConnectionAndPopulateData() throws Exception { return con; } - private void cleanup(Connection con) throws Exception { + @AfterEach + public void terminate() throws Exception { + Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); try { - if (con == null || con.isClosed()) { - con = DriverManager.getConnection(connectionString); - } - - Utils.dropTableIfExists(tableName, con.createStatement()); + Utils.dropTableIfExists(tableName, stmt); } catch (SQLException e) { } - finally { - if (con != null) - con.close(); - } + stmt.close(); + con.close(); } /** @@ -1849,7 +1743,7 @@ public void testNBCROWNullsForLOBs() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1891,7 +1785,7 @@ public void testSparseColumnSetValues() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1934,7 +1828,7 @@ public void testSparseColumnSetIndex() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1951,61 +1845,58 @@ public void testSparseColumnSetForException() throws Exception { } Connection con = null; - try { - con = createConnectionAndPopulateData(); - Statement stmt = con.createStatement(); - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } - catch (Exception e) { + con = createConnectionAndPopulateData(); + Statement stmt = con.createStatement(); - throw new SQLException("testSparseColumnSetForException threw exception: ", e); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } + catch (Exception e) { - } + throw new SQLException("testSparseColumnSetForException threw exception: ", e); - String selectQuery = "SELECT * FROM " + tableName; - ResultSet rs = stmt.executeQuery(selectQuery); - rs.next(); + } - SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - try { - // test that an exception is thrown when result set is closed - rs.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + String selectQuery = "SELECT * FROM " + tableName; + ResultSet rs = stmt.executeQuery(selectQuery); + rs.next(); - // test that an exception is thrown when statement is closed - try { - rs = stmt.executeQuery(selectQuery); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + try { + // test that an exception is thrown when result set is closed + rs.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); + } + catch (SQLException e) { + } - assertEquals(stmt.isClosed(), true, "testSparseColumnSetForException: statement should be closed since resultset is closed."); - stmt.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + // test that an exception is thrown when statement is closed + try { + rs = stmt.executeQuery(selectQuery); + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - // test that an exception is thrown when connection is closed - try { - rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - con.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + assertEquals(stmt.isClosed(), true, "testSparseColumnSetForException: statement should be closed since resultset is closed."); + stmt.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); } - finally { - cleanup(con); + catch (SQLException e) { + } + + // test that an exception is thrown when connection is closed + try { + rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + con.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); + } + catch (SQLException e) { } + } /** @@ -2053,7 +1944,7 @@ public void testNBCRowForAllNulls() throws Exception { } finally { - cleanup(con); + terminate(); } } @@ -2159,7 +2050,7 @@ public void testNBCROWWithRandomAccess() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -2376,24 +2267,7 @@ private void setup() throws Exception { Connection con = DriverManager.getConnection(connectionString); con.setAutoCommit(false); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } - try { - Utils.dropTableIfExists(table2Name, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } - try { - Utils.dropProcedureIfExists(sprocName, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } + try { stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + "') drop trigger " + triggerName); } @@ -2499,6 +2373,21 @@ public void testStatementInsertExecInsert() throws Exception { // which should have affected 1 (new) row in tableName. assertEquals(updateCount, 1, "Wrong update count"); } + + @AfterEach + public void terminate() throws Exception { + Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); + try { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropTableIfExists(table2Name, stmt); + Utils.dropProcedureIfExists(sprocName, stmt); + } + catch (SQLException e) { + } + stmt.close(); + con.close(); + } } @Nested @@ -2514,11 +2403,7 @@ private void setup() throws Exception { Connection con = DriverManager.getConnection(connectionString); con.setAutoCommit(false); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } + try { stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + "') drop trigger " + triggerName); } @@ -2704,6 +2589,19 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Excep pstmt.close(); con.close(); } + + @AfterEach + public void terminate() throws Exception { + Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + } + stmt.close(); + con.close(); + } } @Nested @@ -2728,12 +2626,6 @@ private void setup() throws Exception { throw new SQLException("setup threw exception: ", e); } - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT primary key)"); for (int i = 0; i < NUM_ROWS; i++) stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); @@ -2773,5 +2665,18 @@ public void testNoCountWithExecute() throws Exception { stmt.close(); con.close(); } + + @AfterEach + public void terminate() throws Exception { + Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + } + stmt.close(); + con.close(); + } } } From 328feecd23556de2ae49bd38d859ea0cc11fbaa4 Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Mon, 25 Sep 2017 15:59:43 -0700 Subject: [PATCH 19/68] more cleaning of tables and procedures --- .../unit/statement/CallableMixedTest.java | 21 ++++++++++---- .../jdbc/unit/statement/LimitEscapeTest.java | 12 ++++---- .../jdbc/unit/statement/MergeTest.java | 19 ++++++++---- .../statement/NamedParamMultiPartTest.java | 22 +++++++++----- .../jdbc/unit/statement/PQImpsTest.java | 22 +++++++------- .../jdbc/unit/statement/PoolableTest.java | 29 +++++++++++++++++++ 6 files changed, 89 insertions(+), 36 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java index 95f2962c2..d42cbe610 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java @@ -22,6 +22,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -39,6 +40,7 @@ public class CallableMixedTest extends AbstractTest { /** * Tests Callable mix + * * @throws SQLException */ @Test @@ -67,7 +69,7 @@ public void datatypesTest() throws SQLException { callableStatement.registerOutParameter((int) 1, (int) 4); callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); callableStatement.registerOutParameter((int) 3, (int) 4); - callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); + callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); callableStatement.registerOutParameter((int) 5, (int) 5); callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); @@ -97,13 +99,20 @@ public void datatypesTest() throws SQLException { terminateVariation(); } - + /** + * Cleanups + * @throws SQLException + */ private void terminateVariation() throws SQLException { statement = connection.createStatement(); - statement.executeUpdate("DROP TABLE " + tableName); - statement.executeUpdate(" DROP PROCEDURE " + procName); - statement.close(); - connection.close(); + Utils.dropTableIfExists(tableName, statement); + Utils.dropProcedureIfExists(procName, statement); + if (statement != null) { + statement.close(); + } + if (connection != null) { + connection.close(); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java index cc9e0e69f..6e3563101 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java @@ -32,6 +32,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; /** * Testing with LimitEscape queries @@ -782,13 +783,10 @@ public static void afterAll() throws Exception { Statement stmt = conn.createStatement(); try { - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t1', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t1"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t2', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t2"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t3', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t3"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t4', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t4"); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t4", stmt); } catch (Exception ex) { fail(ex.toString()); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java index 43b0bccc1..3cb5b2e78 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java @@ -10,7 +10,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; +import java.sql.Connection; +import java.sql.DriverManager; import java.sql.ResultSet; +import java.sql.Statement; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; @@ -21,6 +24,8 @@ import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; +import com.microsoft.sqlserver.testframework.Utils; + /** * Testing merge queries @@ -77,17 +82,21 @@ public void runTest() throws Exception { @AfterAll public static void afterAll() throws Exception { - DBConnection conn = new DBConnection(connectionString); - DBStatement stmt = conn.createStatement(); + Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement(); try { - stmt.executeUpdate("IF OBJECT_ID (N'dbo.CricketTeams', N'U') IS NOT NULL DROP TABLE dbo.CricketTeams"); + Utils.dropTableIfExists("dbo.CricketTeams", stmt); } catch (Exception ex) { fail(ex.toString()); } finally { - stmt.close(); - conn.close(); + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java index be8139e39..c264ffe4a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java @@ -32,10 +32,10 @@ */ @RunWith(JUnitPlatform.class) public class NamedParamMultiPartTest extends AbstractTest { - private static final String dataPut = "eminem "; + private static final String dataPut = "eminem"; private static Connection connection = null; private static CallableStatement cs = null; - + String procedureName = "mystoredproc"; /** * setup * @throws SQLException @@ -54,7 +54,7 @@ public static void beforeAll() throws SQLException { */ @Test public void update1() throws Exception { - cs = connection.prepareCall("{ CALL [mystoredproc] (?) }"); + cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); String data = cs.getString("p_out"); @@ -67,7 +67,7 @@ public void update1() throws Exception { */ @Test public void update2() throws Exception { - cs = connection.prepareCall("{ CALL [dbo].[mystoredproc] (?) }"); + cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -95,7 +95,7 @@ public void update3() throws Exception { */ @Test public void update4() throws Exception { - cs = connection.prepareCall("{ CALL mystoredproc (?) }"); + cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -108,7 +108,7 @@ public void update4() throws Exception { */ @Test public void update5() throws Exception { - cs = connection.prepareCall("{ CALL dbo.mystoredproc (?) }"); + cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -122,7 +122,7 @@ public void update5() throws Exception { @Test public void update6() throws Exception { String catalog = connection.getCatalog(); - String storedproc = catalog + ".dbo.mystoredproc"; + String storedproc = catalog + ".dbo."+procedureName; cs = connection.prepareCall("{ CALL " + storedproc + " (?) }"); cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); @@ -132,10 +132,16 @@ public void update6() throws Exception { /** * Clean up + * @throws SQLException */ @AfterAll - public static void afterAll() { + public static void afterAll() throws SQLException { + Statement stmt = connection.createStatement(); + Utils.dropProcedureIfExists("mystoredproc", stmt); try { + if (null != stmt) { + stmt.close(); + } if (null != connection) { connection.close(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java index 15fce3fe5..7d786dc46 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java @@ -30,6 +30,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerParameterMetaData; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -1380,16 +1381,17 @@ public void testComplexQueryWithMultipleTables() throws SQLServerException { */ @AfterAll public static void dropTables() throws SQLException { - stmt.execute("if object_id('" + nameTable + "','U') is not null" + " drop table " + nameTable); - stmt.execute("if object_id('" + phoneNumberTable + "','U') is not null" + " drop table " + phoneNumberTable); - stmt.execute("if object_id('" + mergeNameDesTable + "','U') is not null" + " drop table " + mergeNameDesTable); - stmt.execute("if object_id('" + numericTable + "','U') is not null" + " drop table " + numericTable); - stmt.execute("if object_id('" + charTable + "','U') is not null" + " drop table " + charTable); - stmt.execute("if object_id('" + charTable2 + "','U') is not null" + " drop table " + charTable2); - stmt.execute("if object_id('" + binaryTable + "','U') is not null" + " drop table " + binaryTable); - stmt.execute("if object_id('" + dateAndTimeTable + "','U') is not null" + " drop table " + dateAndTimeTable); - stmt.execute("if object_id('" + multipleTypesTable + "','U') is not null" + " drop table " + multipleTypesTable); - stmt.execute("if object_id('" + spaceTable + "','U') is not null" + " drop table " + spaceTable); + Utils.dropTableIfExists(nameTable, stmt); + Utils.dropTableIfExists(phoneNumberTable, stmt); + Utils.dropTableIfExists(mergeNameDesTable, stmt); + Utils.dropTableIfExists(numericTable, stmt); + Utils.dropTableIfExists(phoneNumberTable, stmt); + Utils.dropTableIfExists(charTable, stmt); + Utils.dropTableIfExists(charTable2, stmt); + Utils.dropTableIfExists(binaryTable, stmt); + Utils.dropTableIfExists(dateAndTimeTable, stmt); + Utils.dropTableIfExists(multipleTypesTable, stmt); + Utils.dropTableIfExists(spaceTable, stmt); if (null != rs) { rs.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java index 626efeb99..2a2f69a3f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java @@ -8,6 +8,7 @@ package com.microsoft.sqlserver.jdbc.unit.statement; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.sql.CallableStatement; import java.sql.Connection; @@ -16,6 +17,7 @@ import java.sql.SQLException; import java.sql.Statement; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; @@ -25,6 +27,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; /** * Test Poolable statements @@ -75,4 +78,30 @@ public void poolableTest() throws SQLException, ClassNotFoundException { } } + /** + * Clean up + * + * @throws Exception + */ + @AfterAll + public static void afterAll() throws Exception { + + Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement(); + try { + Utils.dropProcedureIfExists("ProcName", stmt); + } + catch (Exception ex) { + fail(ex.toString()); + } + finally { + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } + } + } From e55a13c9ed68d098acf14b9dcc37544a68655547 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Tue, 26 Sep 2017 11:58:45 -0700 Subject: [PATCH 20/68] add snapshot to pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 968bfada3..550056e71 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.3 + 6.3.3-SNAPSHOT jar From 1341a9ff02b030532dd0c2a237e05915ced07fe0 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Tue, 26 Sep 2017 12:01:01 -0700 Subject: [PATCH 21/68] Make it 6.3.4 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 550056e71..296eb209e 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.3-SNAPSHOT + 6.3.4-SNAPSHOT jar From e77a046c55097c71f9ce063c8ee603480f7576ac Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Tue, 26 Sep 2017 14:33:51 -0700 Subject: [PATCH 22/68] Implement checkDuplicateColumnName to check duplicate columns --- .../sqlserver/jdbc/SQLServerDataTable.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index d3f176a31..939ac5163 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -13,10 +13,12 @@ import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.UUID; public final class SQLServerDataTable { @@ -24,6 +26,7 @@ public final class SQLServerDataTable { int rowCount = 0; int columnCount = 0; Map columnMetadata = null; + Set columnList = null; Map rows = null; private String tvpName = null; @@ -37,6 +40,7 @@ public final class SQLServerDataTable { // Name used in CREATE TYPE public SQLServerDataTable() throws SQLServerException { columnMetadata = new LinkedHashMap<>(); + columnList = new HashSet<>(); rows = new HashMap<>(); } @@ -75,7 +79,7 @@ public synchronized Iterator> getIterator() { public synchronized void addColumnMetadata(String columnName, int sqlType) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(columnName, columnMetadata); + checkDuplicateColumnName(columnName); columnMetadata.put(columnCount++, new SQLServerDataColumn(columnName, sqlType)); } @@ -89,10 +93,29 @@ public synchronized void addColumnMetadata(String columnName, */ public synchronized void addColumnMetadata(SQLServerDataColumn column) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(column.columnName, columnMetadata); + checkDuplicateColumnName(column.columnName); columnMetadata.put(columnCount++, column); } + /** + * Checks if duplicate columns exists, in O(n) time. + * + * @param columnName + * the name of the column + * @throws SQLServerException + * when a duplicate column exists + */ + private void checkDuplicateColumnName(String columnName) throws SQLServerException { + if (null != columnList) { + //columnList.add will return false if the same column name already exists + if (!columnList.add(columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); + } + } + } + /** * Adds one row of data to the data table. * From 8f69956400134ad0e10aadc94ed2eb5dee9ef980 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Wed, 27 Sep 2017 14:42:36 -0700 Subject: [PATCH 23/68] Revert "Implement checkDuplicateColumnName to check duplicate columns" This reverts commit e77a046c55097c71f9ce063c8ee603480f7576ac. --- .../sqlserver/jdbc/SQLServerDataTable.java | 27 ++----------------- 1 file changed, 2 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index 939ac5163..d3f176a31 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -13,12 +13,10 @@ import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.Set; import java.util.UUID; public final class SQLServerDataTable { @@ -26,7 +24,6 @@ public final class SQLServerDataTable { int rowCount = 0; int columnCount = 0; Map columnMetadata = null; - Set columnList = null; Map rows = null; private String tvpName = null; @@ -40,7 +37,6 @@ public final class SQLServerDataTable { // Name used in CREATE TYPE public SQLServerDataTable() throws SQLServerException { columnMetadata = new LinkedHashMap<>(); - columnList = new HashSet<>(); rows = new HashMap<>(); } @@ -79,7 +75,7 @@ public synchronized Iterator> getIterator() { public synchronized void addColumnMetadata(String columnName, int sqlType) throws SQLServerException { // column names must be unique - checkDuplicateColumnName(columnName); + Util.checkDuplicateColumnName(columnName, columnMetadata); columnMetadata.put(columnCount++, new SQLServerDataColumn(columnName, sqlType)); } @@ -93,29 +89,10 @@ public synchronized void addColumnMetadata(String columnName, */ public synchronized void addColumnMetadata(SQLServerDataColumn column) throws SQLServerException { // column names must be unique - checkDuplicateColumnName(column.columnName); + Util.checkDuplicateColumnName(column.columnName, columnMetadata); columnMetadata.put(columnCount++, column); } - /** - * Checks if duplicate columns exists, in O(n) time. - * - * @param columnName - * the name of the column - * @throws SQLServerException - * when a duplicate column exists - */ - private void checkDuplicateColumnName(String columnName) throws SQLServerException { - if (null != columnList) { - //columnList.add will return false if the same column name already exists - if (!columnList.add(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } - } - /** * Adds one row of data to the data table. * From f8e89dfeb58623f3e1827f444afe8df7ce172be7 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Wed, 27 Sep 2017 15:00:53 -0700 Subject: [PATCH 24/68] Revert "Revert "Implement checkDuplicateColumnName to check duplicate columns"" This reverts commit 8f69956400134ad0e10aadc94ed2eb5dee9ef980. --- .../sqlserver/jdbc/SQLServerDataTable.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index d3f176a31..939ac5163 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -13,10 +13,12 @@ import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.UUID; public final class SQLServerDataTable { @@ -24,6 +26,7 @@ public final class SQLServerDataTable { int rowCount = 0; int columnCount = 0; Map columnMetadata = null; + Set columnList = null; Map rows = null; private String tvpName = null; @@ -37,6 +40,7 @@ public final class SQLServerDataTable { // Name used in CREATE TYPE public SQLServerDataTable() throws SQLServerException { columnMetadata = new LinkedHashMap<>(); + columnList = new HashSet<>(); rows = new HashMap<>(); } @@ -75,7 +79,7 @@ public synchronized Iterator> getIterator() { public synchronized void addColumnMetadata(String columnName, int sqlType) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(columnName, columnMetadata); + checkDuplicateColumnName(columnName); columnMetadata.put(columnCount++, new SQLServerDataColumn(columnName, sqlType)); } @@ -89,10 +93,29 @@ public synchronized void addColumnMetadata(String columnName, */ public synchronized void addColumnMetadata(SQLServerDataColumn column) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(column.columnName, columnMetadata); + checkDuplicateColumnName(column.columnName); columnMetadata.put(columnCount++, column); } + /** + * Checks if duplicate columns exists, in O(n) time. + * + * @param columnName + * the name of the column + * @throws SQLServerException + * when a duplicate column exists + */ + private void checkDuplicateColumnName(String columnName) throws SQLServerException { + if (null != columnList) { + //columnList.add will return false if the same column name already exists + if (!columnList.add(columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); + } + } + } + /** * Adds one row of data to the data table. * From 91a3eea6e3cc3bb75dda4630e066b03da84f4789 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Wed, 27 Sep 2017 15:07:36 -0700 Subject: [PATCH 25/68] Apply same logic for TVP --- src/main/java/com/microsoft/sqlserver/jdbc/TVP.java | 13 ++++++++++++- .../java/com/microsoft/sqlserver/jdbc/Util.java | 2 ++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java index 6f68d685a..21f2c061d 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java @@ -12,10 +12,12 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.MessageFormat; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; enum TVPType { ResultSet, @@ -48,6 +50,7 @@ class TVP { Iterator> sourceDataTableRowIterator = null; ISQLServerDataRecord sourceRecord = null; TVPType tvpType = null; + Set columnList = null; // MultiPartIdentifierState enum MPIState { @@ -94,6 +97,7 @@ void initTVP(TVPType type, ISQLServerDataRecord tvpRecord) throws SQLServerException { initTVP(TVPType.ISQLServerDataRecord, tvpPartName); sourceRecord = tvpRecord; + columnList = new HashSet<>(); // Populate TVP metdata from ISQLServerDataRecord. populateMetadataFromDataRecord(); @@ -186,7 +190,14 @@ void populateMetadataFromDataRecord() throws SQLServerException { } for (int i = 0; i < sourceRecord.getColumnCount(); i++) { // Make a copy here as we do not want to change user's metadata. - Util.checkDuplicateColumnName(sourceRecord.getColumnMetaData(i + 1).columnName, columnMetadata); + if (null != columnList) { + //columnList.add will return false if the same column name already exists + if (!columnList.add(sourceRecord.getColumnMetaData(i + 1).columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {sourceRecord.getColumnMetaData(i + 1).columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); + } + } SQLServerMetaData metaData = new SQLServerMetaData(sourceRecord.getColumnMetaData(i + 1)); columnMetadata.put(i, metaData); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java index db10ebce1..ad43f0f74 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java @@ -558,6 +558,7 @@ static String escapeSQLId(String inID) { return outID.toString(); } + /* static void checkDuplicateColumnName(String columnName, Map columnMetadata) throws SQLServerException { if (columnMetadata.get(0) instanceof SQLServerMetaData) { @@ -581,6 +582,7 @@ else if (columnMetadata.get(0) instanceof SQLServerDataColumn) { } } } + */ /** * Reads a UNICODE string from byte buffer at offset (up to byteLength). From 3ac6077703d3c3bc8d4bcdac2114639e7ac06f70 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Fri, 29 Sep 2017 14:02:31 -0700 Subject: [PATCH 26/68] update changelog and readme for dev branch --- CHANGELOG.md | 4 ++++ README.md | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ebc0ce1b..5e909a89d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) - Updated ADAL4J dependency to version 1.2.0 [#392](https://github.com/Microsoft/mssql-jdbc/pull/392) - Updated azure-keyvault dependency to version 1.0.0 [#397](https://github.com/Microsoft/mssql-jdbc/pull/397) +## [6.2.2] Hotfix & Stable Release +### Changed +- Updated ADAL4J to version 1.2.0 and AKV to version 1.0.0 [#516](https://github.com/Microsoft/mssql-jdbc/pull/516) + ## [6.2.1] Hotfix & Stable Release ### Fixed Issues - Fixed queries without parameters using preparedStatement [#372](https://github.com/Microsoft/mssql-jdbc/pull/372) diff --git a/README.md b/README.md index 5bb33d3bd..2196f02d4 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ We're now on the Maven Central Repository. Add the following to your POM file to com.microsoft.sqlserver mssql-jdbc - 6.2.1.jre8 + 6.2.2.jre8 ``` The driver can be downloaded from the [Microsoft Download Center](https://go.microsoft.com/fwlink/?linkid=852460). @@ -130,7 +130,7 @@ Projects that require either of the two features need to explicitly declare the 1.0.0 ``` -***Please note*** as of the v6.3.0-preview, the way to construct a `SQLServerColumnEncryptionAzureKeyVaultProvider` object has changed. Please refer to this [Wiki](https://github.com/Microsoft/mssql-jdbc/wiki/New-Constructor-Definition-for-SQLServerColumnEncryptionAzureKeyVaultProvider-after-6.3.0-Preview-Release) page for more information. +***Please note*** as of the v6.2.2, the way to construct a `SQLServerColumnEncryptionAzureKeyVaultProvider` object has changed. Please refer to this [Wiki](https://github.com/Microsoft/mssql-jdbc/wiki/New-Constructor-Definition-for-SQLServerColumnEncryptionAzureKeyVaultProvider-after-6.2.2-Release) page for more information. ## Guidelines for Creating Pull Requests We love contributions from the community. To help improve the quality of our code, we encourage you to use the mssql-jdbc_formatter.xml formatter provided on all pull requests. From fe83139cdbdccd7fab2c61d6e56a2bb56a5c04ad Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Mon, 2 Oct 2017 13:32:42 -0700 Subject: [PATCH 27/68] use try with resources --- .../unit/statement/CallableMixedTest.java | 94 +++++------ .../jdbc/unit/statement/MergeTest.java | 49 ++---- .../statement/NamedParamMultiPartTest.java | 108 +++++++------ .../jdbc/unit/statement/StatementTest.java | 148 ++++++++---------- .../sqlserver/testframework/DBConnection.java | 2 +- .../sqlserver/testframework/DBStatement.java | 2 +- 6 files changed, 187 insertions(+), 216 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java index d42cbe610..8c7681f27 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java @@ -32,7 +32,6 @@ @RunWith(JUnitPlatform.class) public class CallableMixedTest extends AbstractTest { Connection connection = null; - Statement statement = null; String tableN = RandomUtil.getIdentifier("TFOO3"); String procN = RandomUtil.getIdentifier("SPFOO3"); String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); @@ -46,73 +45,64 @@ public class CallableMixedTest extends AbstractTest { @Test @DisplayName("Test CallableMix") public void datatypesTest() throws SQLException { - connection = DriverManager.getConnection(connectionString); - statement = connection.createStatement(); + try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement();) { + try { + statement.executeUpdate("DROP TABLE " + tableName); + statement.executeUpdate(" DROP PROCEDURE " + procName); + } + catch (Exception e) { + } - try { - statement.executeUpdate("DROP TABLE " + tableName); - statement.executeUpdate(" DROP PROCEDURE " + procName); - } - catch (Exception e) { - } + statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); + statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); - statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); - statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); - statement.close(); - Statement stmt = connection.createStatement(); - stmt.executeUpdate("CREATE PROCEDURE " + procName - + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " - + tableName + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - stmt.close(); + statement.executeUpdate("CREATE PROCEDURE " + procName + + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " + + tableName + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }"); - callableStatement.registerOutParameter((int) 1, (int) 4); - callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); - callableStatement.registerOutParameter((int) 3, (int) 4); - callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); - callableStatement.registerOutParameter((int) 5, (int) 5); - callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); + try (CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }")) { + callableStatement.registerOutParameter((int) 1, (int) 4); + callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); + callableStatement.registerOutParameter((int) 3, (int) 4); + callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); + callableStatement.registerOutParameter((int) 5, (int) 5); + callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); - // get results and a value - ResultSet rs = callableStatement.executeQuery(); - rs.next(); + // get results and a value + ResultSet rs = callableStatement.executeQuery(); + rs.next(); - assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); + assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); - // do nothing and reexecute - rs = callableStatement.executeQuery(); - // get the param without getting the resultset - rs = callableStatement.executeQuery(); - assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); + // do nothing and reexecute + rs = callableStatement.executeQuery(); + // get the param without getting the resultset + rs = callableStatement.executeQuery(); + assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); - rs = callableStatement.executeQuery(); - rs.next(); + rs = callableStatement.executeQuery(); + rs.next(); - assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); - rs = callableStatement.executeQuery(); - callableStatement.close(); - rs.close(); - stmt.close(); + assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); + rs = callableStatement.executeQuery(); + rs.close(); + } + } terminateVariation(); } /** * Cleanups + * * @throws SQLException */ private void terminateVariation() throws SQLException { - statement = connection.createStatement(); - Utils.dropTableIfExists(tableName, statement); - Utils.dropProcedureIfExists(procName, statement); - if (statement != null) { - statement.close(); - } - if (connection != null) { - connection.close(); + try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement()) { + Utils.dropTableIfExists(tableName, statement); + Utils.dropProcedureIfExists(procName, statement); } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java index 3cb5b2e78..54ebcdde2 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java @@ -26,7 +26,6 @@ import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.Utils; - /** * Testing merge queries */ @@ -49,56 +48,42 @@ public class MergeTest extends AbstractTest { + "VALUES (SOURCE.CricketTeamID, SOURCE.CricketTeamCountry, SOURCE.CricketTeamContinent) " + "WHEN NOT MATCHED BY SOURCE THEN DELETE;"; - /** * Merge test + * * @throws Exception */ @Test @DisplayName("Merge Test") public void runTest() throws Exception { - DBConnection conn = new DBConnection(connectionString); - if (conn.getServerVersion() >= 10) { - DBStatement stmt = conn.createStatement(); - stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - stmt.executeUpdate(setupTables); - stmt.executeUpdate(mergeCmd2); - int updateCount = stmt.getUpdateCount(); - assertEquals(updateCount, 3, "Received the wrong update count!"); - - if (null != stmt) { - stmt.close(); - } - if (null != conn) { - conn.close(); + try (DBConnection conn = new DBConnection(connectionString)) { + if (conn.getServerVersion() >= 10) { + try (DBStatement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);) { + stmt.executeUpdate(setupTables); + stmt.executeUpdate(mergeCmd2); + int updateCount = stmt.getUpdateCount(); + assertEquals(updateCount, 3, "Received the wrong update count!"); + + } } } } - + /** * Clean up + * * @throws Exception */ @AfterAll public static void afterAll() throws Exception { - Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(); - try { - Utils.dropTableIfExists("dbo.CricketTeams", stmt); - } - catch (Exception ex) { - fail(ex.toString()); - } - finally { - if (stmt != null) { - stmt.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists("dbo.CricketTeams", stmt); } - if (conn != null) { - conn.close(); + catch (Exception ex) { + fail(ex.toString()); } } - } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java index c264ffe4a..2ee818313 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java @@ -34,85 +34,97 @@ public class NamedParamMultiPartTest extends AbstractTest { private static final String dataPut = "eminem"; private static Connection connection = null; - private static CallableStatement cs = null; String procedureName = "mystoredproc"; + /** * setup + * * @throws SQLException */ @BeforeAll public static void beforeAll() throws SQLException { connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement(); - Utils.dropProcedureIfExists("mystoredproc", statement); - statement.executeUpdate("CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); - statement.close(); - } + try (Statement statement = connection.createStatement()) { + Utils.dropProcedureIfExists("mystoredproc", statement); + statement.executeUpdate("CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); + } + } + /** * Stored procedure call + * * @throws Exception */ @Test public void update1() throws Exception { - cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - String data = cs.getString("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + String data = cs.getString("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update2() throws Exception { - cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update3() throws Exception { String catalog = connection.getCatalog(); String storedproc = "[" + catalog + "]" + ".[dbo].[mystoredproc]"; - cs = connection.prepareCall("{ CALL " + storedproc + " (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update4() throws Exception { - cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update5() throws Exception { - cs = connection.prepareCall("{ CALL "+procedureName+" (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** @@ -122,35 +134,29 @@ public void update5() throws Exception { @Test public void update6() throws Exception { String catalog = connection.getCatalog(); - String storedproc = catalog + ".dbo."+procedureName; - cs = connection.prepareCall("{ CALL " + storedproc + " (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + String storedproc = catalog + ".dbo." + procedureName; + try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Clean up - * @throws SQLException + * + * @throws SQLException */ @AfterAll public static void afterAll() throws SQLException { - Statement stmt = connection.createStatement(); - Utils.dropProcedureIfExists("mystoredproc", stmt); - try { - if (null != stmt) { - stmt.close(); - } - if (null != connection) { + try (Statement stmt = connection.createStatement()) { + Utils.dropProcedureIfExists("mystoredproc", stmt); + } + finally { + if (connection != null) { connection.close(); } - if (null != cs) { - cs.close(); - } - } - catch (SQLException e) { - fail(e.toString()); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java index ba033d2aa..afb311ae9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java @@ -1174,18 +1174,15 @@ public void testLargeMaxRowsJDBC42() throws Exception { @AfterEach public void terminate() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(table1Name, stmt); - Utils.dropTableIfExists(table2Name, stmt); - } - catch (SQLException e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(table1Name, stmt); + Utils.dropTableIfExists(table2Name, stmt); + } + catch (SQLException e) { + } } - stmt.close(); - con.close(); } - } @Nested @@ -1311,15 +1308,14 @@ public void testJdbc41CallableStatementMethods() throws Exception { @AfterEach public void terminate() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (SQLException e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropProcedureIfExists(procName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } } - stmt.close(); - con.close(); } } @@ -1664,16 +1660,15 @@ public void testRowError() throws Exception { @AfterEach public void terminate() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - Utils.dropProcedureIfExists(procName, stmt); - } - catch (SQLException e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropProcedureIfExists(procName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } } - stmt.close(); - con.close(); } } @@ -1703,15 +1698,14 @@ private Connection createConnectionAndPopulateData() throws Exception { @AfterEach public void terminate() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } } - stmt.close(); - con.close(); } /** @@ -1840,10 +1834,11 @@ public void testSparseColumnSetIndex() throws Exception { */ @Test public void testSparseColumnSetForException() throws Exception { - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testSparseColumnSetForException skipped for Yukon"); + try (DBConnection conn = new DBConnection(connectionString)) { + if (conn.getServerVersion() <= 9.0) { + log.fine("testSparseColumnSetForException skipped for Yukon"); + } } - Connection con = null; con = createConnectionAndPopulateData(); @@ -2376,17 +2371,16 @@ public void testStatementInsertExecInsert() throws Exception { @AfterEach public void terminate() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - Utils.dropTableIfExists(table2Name, stmt); - Utils.dropProcedureIfExists(sprocName, stmt); - } - catch (SQLException e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropTableIfExists(table2Name, stmt); + Utils.dropProcedureIfExists(sprocName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } } - stmt.close(); - con.close(); } } @@ -2592,15 +2586,14 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Excep @AfterEach public void terminate() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } } - stmt.close(); - con.close(); } } @@ -2644,39 +2637,36 @@ private void setup() throws Exception { @Test public void testNoCountWithExecute() throws Exception { // Ensure lastUpdateCount=true... - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); - Statement stmt = con.createStatement(); - boolean isResultSet = stmt - .execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); + Statement stmt = con.createStatement();) { - assertEquals(true, isResultSet, "execute() said first result was an update count"); + boolean isResultSet = stmt + .execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); - ResultSet rs = stmt.getResultSet(); - while (rs.next()) - ; - rs.close(); + assertEquals(true, isResultSet, "execute() said first result was an update count"); - boolean moreResults = stmt.getMoreResults(); - assertEquals(false, moreResults, "next result is a ResultSet?"); + ResultSet rs = stmt.getResultSet(); + while (rs.next()); + rs.close(); - int updateCount = stmt.getUpdateCount(); - assertEquals(-1, updateCount, "only one result was expected..."); + boolean moreResults = stmt.getMoreResults(); + assertEquals(false, moreResults, "next result is a ResultSet?"); - stmt.close(); - con.close(); + int updateCount = stmt.getUpdateCount(); + assertEquals(-1, updateCount, "only one result was expected..."); + } } @AfterEach public void terminate() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } } - stmt.close(); - con.close(); } } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java index 51e0c7aa2..a6ae11d07 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java @@ -21,7 +21,7 @@ /* * Wrapper class for SQLServerConnection */ -public class DBConnection extends AbstractParentWrapper { +public class DBConnection extends AbstractParentWrapper implements AutoCloseable { private double serverversion = 0; // TODO: add Isolation Level diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java index 8d4787120..5ae1d20e2 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java @@ -21,7 +21,7 @@ * @author Microsoft * */ -public class DBStatement extends AbstractParentWrapper { +public class DBStatement extends AbstractParentWrapper implements AutoCloseable { // TODO: support PreparedStatement and CallableStatement // TODO: add stmt level holdability From 7f188108238278df5492601ff1153c6502ded3b4 Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Mon, 2 Oct 2017 13:39:44 -0700 Subject: [PATCH 28/68] add another try-with-resource --- .../jdbc/unit/statement/PoolableTest.java | 76 ++++++++----------- 1 file changed, 33 insertions(+), 43 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java index 2a2f69a3f..7ce0773de 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java @@ -38,46 +38,45 @@ public class PoolableTest extends AbstractTest { /** * Poolable Test + * * @throws SQLException * @throws ClassNotFoundException */ @Test @DisplayName("Poolable Test") - public void poolableTest() throws SQLException, ClassNotFoundException { - Connection connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement(); - try { - // First get the default values - boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); - assertEquals(isPoolable, false, "SQLServerStatement should not be Poolable by default"); - - PreparedStatement prepStmt = connection.prepareStatement("select 1"); - isPoolable = ((SQLServerPreparedStatement) prepStmt).isPoolable(); - assertEquals(isPoolable, true, "SQLServerPreparedStatement should be Poolable by default"); - + public void poolableTest() throws SQLException, ClassNotFoundException { + try (Connection conn = DriverManager.getConnection(connectionString); Statement statement = conn.createStatement()) { + try { + // First get the default values + boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); + assertEquals(isPoolable, false, "SQLServerStatement should not be Poolable by default"); - CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }"); - isPoolable = ((SQLServerCallableStatement) callableStatement).isPoolable(); + try (PreparedStatement prepStmt = connection.prepareStatement("select 1")) { + isPoolable = ((SQLServerPreparedStatement) prepStmt).isPoolable(); + assertEquals(isPoolable, true, "SQLServerPreparedStatement should be Poolable by default"); + } - assertEquals(isPoolable, true, "SQLServerCallableStatement should be Poolable by default"); + try (CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }");) { + isPoolable = ((SQLServerCallableStatement) callableStatement).isPoolable(); - // Now do couple of sets and gets + assertEquals(isPoolable, true, "SQLServerCallableStatement should be Poolable by default"); - ((SQLServerCallableStatement) callableStatement).setPoolable(false); - assertEquals(((SQLServerCallableStatement) callableStatement).isPoolable(), false, "set did not work"); - callableStatement.close(); + // Now do couple of sets and gets - ((SQLServerStatement) statement).setPoolable(true); - assertEquals(((SQLServerStatement) statement).isPoolable(), true, "set did not work"); - statement.close(); + ((SQLServerCallableStatement) callableStatement).setPoolable(false); + assertEquals(((SQLServerCallableStatement) callableStatement).isPoolable(), false, "set did not work"); + } + ((SQLServerStatement) statement).setPoolable(true); + assertEquals(((SQLServerStatement) statement).isPoolable(), true, "set did not work"); + } + catch (UnsupportedOperationException e) { + assertEquals(System.getProperty("java.specification.version"), "1.5", "PoolableTest should be supported in anything other than 1.5"); + assertEquals(e.getMessage(), "This operation is not supported.", "Wrong exception message"); + } } - catch (UnsupportedOperationException e) { - assertEquals(System.getProperty("java.specification.version"), "1.5", "PoolableTest should be supported in anything other than 1.5"); - assertEquals(e.getMessage(), "This operation is not supported.", "Wrong exception message"); - } - } - + } + /** * Clean up * @@ -85,23 +84,14 @@ public void poolableTest() throws SQLException, ClassNotFoundException { */ @AfterAll public static void afterAll() throws Exception { - - Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(); - try { - Utils.dropProcedureIfExists("ProcName", stmt); - } - catch (Exception ex) { - fail(ex.toString()); - } - finally { - if (stmt != null) { - stmt.close(); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try { + Utils.dropProcedureIfExists("ProcName", stmt); } - if (conn != null) { - conn.close(); + catch (Exception ex) { + fail(ex.toString()); } } } - + } From d778a6f90e62dfa41b5c5ddf416168929ab6142e Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Mon, 2 Oct 2017 13:48:18 -0700 Subject: [PATCH 29/68] drop a not needed method --- .../sqlserver/jdbc/unit/statement/CallableMixedTest.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java index 8c7681f27..2fff7da55 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java @@ -46,12 +46,6 @@ public class CallableMixedTest extends AbstractTest { @DisplayName("Test CallableMix") public void datatypesTest() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement();) { - try { - statement.executeUpdate("DROP TABLE " + tableName); - statement.executeUpdate(" DROP PROCEDURE " + procName); - } - catch (Exception e) { - } statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); From ada51de81330e8a778fe5afac0d42ffa4c5bb9ef Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Mon, 2 Oct 2017 15:37:16 -0700 Subject: [PATCH 30/68] try-with-resources implementation commit 1 --- .../jdbc/AlwaysEncrypted/AESetup.java | 2219 ++++++++--------- .../CallableStatementTest.java | 576 ++--- 2 files changed, 1299 insertions(+), 1496 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java index 6fc795a98..bfacd630b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -80,8 +80,6 @@ public class AESetup extends AbstractTest { static SQLServerColumnEncryptionKeyStoreProvider storeProvider = null; static SQLServerStatementColumnEncryptionSetting stmtColEncSetting = null; - private static SQLServerPreparedStatement pstmt = null; - /** * Create connection, statement and generate path of resource file * @@ -94,26 +92,28 @@ static void setUpConnection() throws TestAbortedException, Exception { "Aborting test case as SQL Server version is not compatible with Always encrypted "); String AETestConenctionString = connectionString + ";sendTimeAsDateTime=false"; - readFromFile(javaKeyStoreInputFile, "Alias name"); - con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); - stmt = (SQLServerStatement) con.createStatement(); - dropCEK(); - dropCMK(); - con.close(); - + + try(SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropCEK(); + dropCMK(); + } + keyPath = Utils.getCurrentClassPath() + jksName; storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, secretstrJks.toCharArray()); stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.Enabled; + Properties info = new Properties(); info.setProperty("ColumnEncryptionSetting", "Enabled"); info.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); info.setProperty("keyStoreLocation", keyPath); info.setProperty("keyStoreSecret", secretstrJks); + con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString, info); stmt = (SQLServerStatement) con.createStatement(); createCMK(keyStoreName, javaKeyAliases); - createCEK(storeProvider); + createCEK(storeProvider); } /** @@ -140,33 +140,26 @@ private static void dropAll() throws SQLServerException, SQLException { */ private static void readFromFile(String inputFile, String lookupValue) throws IOException { - BufferedReader buffer = null; filePath = Utils.getCurrentClassPath(); try { File f = new File(filePath + inputFile); assumeTrue(f.exists(), "Aborting test case since no java key store and alias name exists!"); - buffer = new BufferedReader(new FileReader(f)); - String readLine = ""; - String[] linecontents; - - while ((readLine = buffer.readLine()) != null) { - if (readLine.trim().contains(lookupValue)) { - linecontents = readLine.split(" "); - javaKeyAliases = linecontents[2]; - break; - } + try(BufferedReader buffer = new BufferedReader(new FileReader(f))) { + String readLine = ""; + String[] linecontents; + + while ((readLine = buffer.readLine()) != null) { + if (readLine.trim().contains(lookupValue)) { + linecontents = readLine.split(" "); + javaKeyAliases = linecontents[2]; + break; + } + } } - } catch (IOException e) { fail(e.toString()); } - finally { - if (null != buffer) { - buffer.close(); - } - } - } /** @@ -744,60 +737,60 @@ protected static void dropTables(SQLServerStatement statement) throws SQLExcepti protected static void populateBinaryNormalCase(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary20 - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(0)); - } - } - - // varbinary50 - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(1)); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(2)); - } - } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(3)); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary20 + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(0)); + } + } + + // varbinary50 + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(1)); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(2)); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(3)); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(4)); + } + } + + pstmt.execute(); } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(4)); - } - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -809,60 +802,60 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th protected static void populateBinarySetObject(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary(20) - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(0)); - } - } - - // varbinary(50) - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(1)); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary(20) + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(0)); + } + } + + // varbinary(50) + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(1)); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(2)); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(3)); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(4)); + } + } + + pstmt.execute(); } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(2)); - } - } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(3)); - } - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(4)); - } - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -874,60 +867,60 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr protected static void populateBinarySetObjectWithJDBCType(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary(20) - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(0), JDBCType.BINARY); - } - } - - // varbinary(50) - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(1), JDBCType.VARBINARY); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(2), JDBCType.VARBINARY); - } - } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(3), JDBCType.BINARY); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary(20) + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(0), JDBCType.BINARY); + } + } + + // varbinary(50) + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(1), JDBCType.VARBINARY); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(2), JDBCType.VARBINARY); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(3), JDBCType.BINARY); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(4), JDBCType.VARBINARY); + } + } + + pstmt.execute(); } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(4), JDBCType.VARBINARY); - } - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -938,30 +931,30 @@ protected static void populateBinarySetObjectWithJDBCType(LinkedList byt protected static void populateBinaryNullCase() throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.BINARY); - } - - // varbinary, varbinary(max) - for (int i = 4; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.VARBINARY); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.BINARY); + } + + // varbinary, varbinary(max) + for (int i = 4; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.VARBINARY); + } + + // binary512 + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.BINARY); + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, java.sql.Types.VARBINARY); + } + + pstmt.execute(); } - - // binary512 - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.BINARY); - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, java.sql.Types.VARBINARY); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -974,60 +967,60 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setString(i, charValues[0]); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setString(i, charValues[1]); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setString(i, charValues[2]); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setNString(i, charValues[3]); - } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setNString(i, charValues[4]); - } - - // varchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setNString(i, charValues[5]); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setString(i, charValues[0]); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setString(i, charValues[1]); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setString(i, charValues[2]); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setNString(i, charValues[3]); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setNString(i, charValues[4]); + } + + // varchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setNString(i, charValues[5]); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + if (null == charValues[6]) { + pstmt.setUniqueIdentifier(i, null); + } + else { + pstmt.setUniqueIdentifier(i, uid); + } + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setString(i, charValues[7]); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setNString(i, charValues[8]); + } + + pstmt.execute(); } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - if (null == charValues[6]) { - pstmt.setUniqueIdentifier(i, null); - } - else { - pstmt.setUniqueIdentifier(i, uid); - } - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setString(i, charValues[7]); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setNString(i, charValues[8]); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1040,55 +1033,55 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, charValues[0]); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, charValues[1]); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, charValues[0]); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, charValues[1]); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, charValues[2], java.sql.Types.LONGVARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, charValues[3], java.sql.Types.NCHAR); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, charValues[4], java.sql.Types.NCHAR); + } + + // nvarchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, charValues[5], java.sql.Types.LONGNVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, charValues[7]); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, charValues[8], java.sql.Types.NCHAR); + } + + pstmt.execute(); } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, charValues[2], java.sql.Types.LONGVARCHAR); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, charValues[3], java.sql.Types.NCHAR); - } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, charValues[4], java.sql.Types.NCHAR); - } - - // nvarchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, charValues[5], java.sql.Types.LONGNVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, charValues[7]); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, charValues[8], java.sql.Types.NCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1101,55 +1094,55 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, charValues[0], JDBCType.CHAR); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, charValues[1], JDBCType.VARCHAR); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, charValues[2], JDBCType.LONGVARCHAR); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, charValues[3], JDBCType.NCHAR); - } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, charValues[4], JDBCType.NVARCHAR); - } - - // nvarchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, charValues[5], JDBCType.LONGNVARCHAR); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, charValues[0], JDBCType.CHAR); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, charValues[1], JDBCType.VARCHAR); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, charValues[2], JDBCType.LONGVARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, charValues[3], JDBCType.NCHAR); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, charValues[4], JDBCType.NVARCHAR); + } + + // nvarchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, charValues[5], JDBCType.LONGNVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, charValues[7], JDBCType.VARCHAR); + } + + // vnarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, charValues[8], JDBCType.NVARCHAR); + } + + pstmt.execute(); } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, charValues[7], JDBCType.VARCHAR); - } - - // vnarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, charValues[8], JDBCType.NVARCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1161,46 +1154,46 @@ protected static void populateCharNullCase() throws SQLException { String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.CHAR); - } - - // varchar, varchar(max) - for (int i = 4; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.VARCHAR); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.CHAR); + } + + // varchar, varchar(max) + for (int i = 4; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.VARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.NCHAR); + } + + // nvarchar, varchar(max) + for (int i = 13; i <= 18; i++) { + pstmt.setNull(i, java.sql.Types.NVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setNull(i, microsoft.sql.Types.GUID); + + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setNull(i, java.sql.Types.VARCHAR); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setNull(i, java.sql.Types.NVARCHAR); + } + + pstmt.execute(); } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.NCHAR); - } - - // nvarchar, varchar(max) - for (int i = 13; i <= 18; i++) { - pstmt.setNull(i, java.sql.Types.NVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setNull(i, microsoft.sql.Types.GUID); - - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setNull(i, java.sql.Types.VARCHAR); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setNull(i, java.sql.Types.NVARCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1212,40 +1205,40 @@ protected static void populateCharNullCase() throws SQLException { protected static void populateDateNormalCase(LinkedList dateValues) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setDate(i, (Date) dateValues.get(0)); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setDate(i, (Date) dateValues.get(0)); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, (Time) dateValues.get(3)); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setDateTime(i, (Timestamp) dateValues.get(4)); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setSmallDateTime(i, (Timestamp) dateValues.get(5)); + } + + pstmt.execute(); } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, (Time) dateValues.get(3)); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setDateTime(i, (Timestamp) dateValues.get(4)); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setSmallDateTime(i, (Timestamp) dateValues.get(5)); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1257,25 +1250,25 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro protected static void populateDateScaleNormalCase(LinkedList dateValues) throws SQLException { String sql = "insert into " + scaleDateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(2) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); - } - - // time(2) - for (int i = 4; i <= 6; i++) { - pstmt.setTime(i, (Time) dateValues.get(5), 2); - } - - // datetimeoffset(2) - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(2) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); + } + + // time(2) + for (int i = 4; i <= 6; i++) { + pstmt.setTime(i, (Time) dateValues.get(5), 2); + } + + // datetimeoffset(2) + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1293,60 +1286,60 @@ protected static void populateDateSetObject(LinkedList dateValues, String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Date) dateValues.get(0), java.sql.Types.DATE); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Date) dateValues.get(0), JDBCType.DATE); - else - pstmt.setObject(i, (Date) dateValues.get(0)); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Timestamp) dateValues.get(1), java.sql.Types.TIMESTAMP); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Timestamp) dateValues.get(1), JDBCType.TIMESTAMP); - else - pstmt.setObject(i, (Timestamp) dateValues.get(1)); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); - else - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2)); - } - - // time default - for (int i = 10; i <= 12; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Time) dateValues.get(3), java.sql.Types.TIME); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Time) dateValues.get(3), JDBCType.TIME); - else - pstmt.setObject(i, (Time) dateValues.get(3)); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, (Timestamp) dateValues.get(4), microsoft.sql.Types.DATETIME); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, (Timestamp) dateValues.get(5), microsoft.sql.Types.SMALLDATETIME); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Date) dateValues.get(0), java.sql.Types.DATE); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Date) dateValues.get(0), JDBCType.DATE); + else + pstmt.setObject(i, (Date) dateValues.get(0)); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Timestamp) dateValues.get(1), java.sql.Types.TIMESTAMP); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Timestamp) dateValues.get(1), JDBCType.TIMESTAMP); + else + pstmt.setObject(i, (Timestamp) dateValues.get(1)); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); + else + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2)); + } + + // time default + for (int i = 10; i <= 12; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Time) dateValues.get(3), java.sql.Types.TIME); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Time) dateValues.get(3), JDBCType.TIME); + else + pstmt.setObject(i, (Time) dateValues.get(3)); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, (Timestamp) dateValues.get(4), microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, (Timestamp) dateValues.get(5), microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1357,40 +1350,40 @@ else if (setter.equalsIgnoreCase("setwithJDBCType")) protected void populateDateSetObjectNull() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.DATE); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.DATE); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIME); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1401,40 +1394,40 @@ protected void populateDateSetObjectNull() throws SQLException { protected static void populateDateNullCase() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.DATE); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setNull(i, java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setNull(i, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.TIME); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, microsoft.sql.Types.DATETIME); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.DATE); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setNull(i, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setNull(i, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.TIME); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setNull(i, microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setNull(i, microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1447,101 +1440,101 @@ protected static void populateNumeric(String[] values) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setShort(i, Short.valueOf(values[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setShort(i, Short.valueOf(values[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setInt(i, Integer.valueOf(values[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setLong(i, Long.valueOf(values[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.valueOf(values[5])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setShort(i, Short.valueOf(values[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setShort(i, Short.valueOf(values[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setInt(i, Integer.valueOf(values[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setLong(i, Long.valueOf(values[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.valueOf(values[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.valueOf(values[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.valueOf(values[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (values[8].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(values[8]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (values[10].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(values[10]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[11]), 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, new BigDecimal(values[12])); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setMoney(i, new BigDecimal(values[13])); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[14]), 28, 4); + } + + // numeric(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[15]), 28, 4); + } + + pstmt.execute(); } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.valueOf(values[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.valueOf(values[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (values[8].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(values[8]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (values[10].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(values[10]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[11]), 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, new BigDecimal(values[12])); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setMoney(i, new BigDecimal(values[13])); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[14]), 28, 4); - } - - // numeric(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[15]), 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1554,101 +1547,101 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setObject(i, true); - } - else { - pstmt.setObject(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, Short.valueOf(values[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, Short.valueOf(values[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, Integer.valueOf(values[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, Long.valueOf(values[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, Double.valueOf(values[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, Double.valueOf(values[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, Float.valueOf(values[7])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setObject(i, true); + } + else { + pstmt.setObject(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, Short.valueOf(values[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, Short.valueOf(values[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, Integer.valueOf(values[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, Long.valueOf(values[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, Double.valueOf(values[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, Double.valueOf(values[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, Float.valueOf(values[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1661,101 +1654,101 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setObject(i, true); - } - else { - pstmt.setObject(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, Short.valueOf(values[1]), JDBCType.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, Short.valueOf(values[2]), JDBCType.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, Integer.valueOf(values[3]), JDBCType.INTEGER); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setObject(i, true); + } + else { + pstmt.setObject(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, Short.valueOf(values[1]), JDBCType.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, Short.valueOf(values[2]), JDBCType.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, Integer.valueOf(values[3]), JDBCType.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, Long.valueOf(values[4]), JDBCType.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, Double.valueOf(values[5]), JDBCType.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, Double.valueOf(values[6]), JDBCType.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, Float.valueOf(values[7]), JDBCType.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, Long.valueOf(values[4]), JDBCType.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, Double.valueOf(values[5]), JDBCType.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, Double.valueOf(values[6]), JDBCType.DOUBLE); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, Float.valueOf(values[7]), JDBCType.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1767,90 +1760,90 @@ protected static void populateNumericSetObjectNull() throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.BIT); - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, java.sql.Types.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.INTEGER); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, java.sql.Types.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.BIT); + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, java.sql.Types.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, java.sql.Types.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, null, java.sql.Types.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, null, java.sql.Types.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1865,89 +1858,89 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.BIT); - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setNull(i, java.sql.Types.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.INTEGER); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, java.sql.Types.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setNull(i, java.sql.Types.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setNull(i, java.sql.Types.DOUBLE); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setNull(i, java.sql.Types.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setBigDecimal(i, null); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, null, 10, 5); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.BIT); + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setNull(i, java.sql.Types.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, java.sql.Types.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setNull(i, java.sql.Types.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setNull(i, java.sql.Types.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setNull(i, java.sql.Types.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setBigDecimal(i, null); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, null, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setBigDecimal(i, null); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, null, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, null); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setMoney(i, null); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, null, 28, 4); + } + + // decimal(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, null, 28, 4); + } + pstmt.execute(); } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setBigDecimal(i, null); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, null, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, null); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setMoney(i, null); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, null, 28, 4); - } - - // decimal(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, null, 28, 4); - } - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1962,105 +1955,105 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - if (1 == Integer.valueOf(numericValues[1])) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // smallint - for (int i = 7; i <= 9; i++) { - if (numericValues[2].equalsIgnoreCase("255")) { - pstmt.setByte(i, (byte) 255); - } - else { - pstmt.setByte(i, Byte.valueOf(numericValues[2])); - } - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setShort(i, Short.valueOf(numericValues[3])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (numericValues[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + if (1 == Integer.valueOf(numericValues[1])) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // smallint + for (int i = 7; i <= 9; i++) { + if (numericValues[2].equalsIgnoreCase("255")) { + pstmt.setByte(i, (byte) 255); + } + else { + pstmt.setByte(i, Byte.valueOf(numericValues[2])); + } + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setShort(i, Short.valueOf(numericValues[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setInt(i, Integer.valueOf(numericValues[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.valueOf(numericValues[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.valueOf(numericValues[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.valueOf(numericValues[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[13])); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + } + + pstmt.execute(); } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setInt(i, Integer.valueOf(numericValues[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.valueOf(numericValues[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.valueOf(numericValues[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.valueOf(numericValues[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[13])); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java index 9c23e98c1..cc6a67e29 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -42,9 +42,6 @@ @RunWith(JUnitPlatform.class) public class CallableStatementTest extends AESetup { - private static SQLServerPreparedStatement pstmt = null; - private static SQLServerCallableStatement callableStatement = null; - private static String multiStatementsProcedure = "multiStatementsProcedure"; private static String inputProcedure = "inputProcedure"; @@ -470,118 +467,120 @@ private static void createTables() throws SQLException { private static void populateTable4() throws SQLException { String sql = "insert into " + table4 + " values( " + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + + pstmt.execute(); } - - pstmt.execute(); } private static void populateTable3() throws SQLException { String sql = "insert into " + table3 + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setShort(i, Short.valueOf(numericValues[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setShort(i, Short.parseShort(numericValues[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setLong(i, Long.parseLong(numericValues[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.parseDouble(numericValues[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.parseDouble(numericValues[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.parseFloat(numericValues[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (numericValues[8].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (numericValues[10].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); - } - - // int2 - for (int i = 37; i <= 39; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); - } - // smallmoney - for (int i = 40; i <= 42; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); - } - - // money - for (int i = 43; i <= 45; i++) { - pstmt.setMoney(i, new BigDecimal(numericValues[13])); - } - - // decimal(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); - } - - // numeric(28,4) - for (int i = 49; i <= 51; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (numericValues[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setShort(i, Short.valueOf(numericValues[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setShort(i, Short.parseShort(numericValues[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setLong(i, Long.parseLong(numericValues[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.parseDouble(numericValues[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.parseDouble(numericValues[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.parseFloat(numericValues[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (numericValues[8].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (numericValues[10].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); + } + + // int2 + for (int i = 37; i <= 39; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + // smallmoney + for (int i = 40; i <= 42; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); + } + + // money + for (int i = 43; i <= 45; i++) { + pstmt.setMoney(i, new BigDecimal(numericValues[13])); + } + + // decimal(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); + } + + // numeric(28,4) + for (int i = 49; i <= 51; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + } + + pstmt.execute(); } - - pstmt.execute(); } private void createMultiInsertionSelection() throws SQLException { @@ -600,44 +599,39 @@ private void MultiInsertionSelection() throws SQLException { try { String sql = "{call " + multiStatementsProcedure + " (?,?,?,?,?,?)}"; - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - - // char, varchar - for (int i = 1; i <= 3; i++) { - callableStatement.setString(i, charValues[0]); - } - - for (int i = 4; i <= 6; i++) { - callableStatement.setString(i, charValues[1]); - } - - boolean results = callableStatement.execute(); - - // skip update count which is given by insertion - while (false == results && (-1) != callableStatement.getUpdateCount()) { - results = callableStatement.getMoreResults(); - } - - while (results) { - rs = callableStatement.getResultSet(); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns); - } - rs.close(); - results = callableStatement.getMoreResults(); + try(SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { + + // char, varchar + for (int i = 1; i <= 3; i++) { + callableStatement.setString(i, charValues[0]); + } + + for (int i = 4; i <= 6; i++) { + callableStatement.setString(i, charValues[1]); + } + + boolean results = callableStatement.execute(); + + // skip update count which is given by insertion + while (false == results && (-1) != callableStatement.getUpdateCount()) { + results = callableStatement.getMoreResults(); + } + + while (results) { + try(ResultSet rs = callableStatement.getResultSet()) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + while (rs.next()) { + testGetString(rs, numberOfColumns); + } + } + results = callableStatement.getMoreResults(); + } } } catch (SQLException e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testGetString(ResultSet rs, @@ -675,8 +669,7 @@ private void createInputProcedure() throws SQLException { private void testInputProcedure(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(values[3])); if (RandomData.returnZero) @@ -703,19 +696,14 @@ private void testInputProcedure(String sql, callableStatement.setBigDecimal(14, new BigDecimal(values[14]), 28, 4); callableStatement.setBigDecimal(15, new BigDecimal(values[15]), 28, 4); - SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery(); - rs.next(); - - assertEquals(rs.getString(1), values[3], "" + "Test for input parameter fails.\n"); + try (SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery()) { + rs.next(); + assertEquals(rs.getString(1), values[3], "" + "Test for input parameter fails.\n"); + } } catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createInputProcedure2() throws SQLException { @@ -735,8 +723,7 @@ private void createInputProcedure2() throws SQLException { private void testInputProcedure2(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setString(1, charValues[1]); callableStatement.setUniqueIdentifier(2, charValues[6]); @@ -747,26 +734,21 @@ private void testInputProcedure2(String sql) throws SQLException { callableStatement.setString(7, charValues[7]); callableStatement.setNString(8, charValues[8]); - SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery(); - rs.next(); - - assertEquals(rs.getString(1).trim(), charValues[1], "Test for input parameter fails.\n"); - assertEquals(rs.getUniqueIdentifier(2), charValues[6].toUpperCase(), "Test for input parameter fails.\n"); - assertEquals(rs.getString(3).trim(), charValues[2], "Test for input parameter fails.\n"); - assertEquals(rs.getString(4).trim(), charValues[3], "Test for input parameter fails.\n"); - assertEquals(rs.getString(5).trim(), charValues[4], "Test for input parameter fails.\n"); - assertEquals(rs.getString(6).trim(), charValues[5], "Test for input parameter fails.\n"); - assertEquals(rs.getString(7).trim(), charValues[7], "Test for input parameter fails.\n"); - assertEquals(rs.getString(8).trim(), charValues[8], "Test for input parameter fails.\n"); + try (SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery()) { + rs.next(); + assertEquals(rs.getString(1).trim(), charValues[1], "Test for input parameter fails.\n"); + assertEquals(rs.getUniqueIdentifier(2), charValues[6].toUpperCase(), "Test for input parameter fails.\n"); + assertEquals(rs.getString(3).trim(), charValues[2], "Test for input parameter fails.\n"); + assertEquals(rs.getString(4).trim(), charValues[3], "Test for input parameter fails.\n"); + assertEquals(rs.getString(5).trim(), charValues[4], "Test for input parameter fails.\n"); + assertEquals(rs.getString(6).trim(), charValues[5], "Test for input parameter fails.\n"); + assertEquals(rs.getString(7).trim(), charValues[7], "Test for input parameter fails.\n"); + assertEquals(rs.getString(8).trim(), charValues[8], "Test for input parameter fails.\n"); + } } catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure3() throws SQLException { @@ -782,8 +764,7 @@ private void createOutputProcedure3() throws SQLException { private void testOutputProcedure3RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -808,17 +789,11 @@ private void testOutputProcedure3RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure3Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -834,17 +809,11 @@ private void testOutputProcedure3Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -860,11 +829,6 @@ private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure2() throws SQLException { @@ -885,8 +849,7 @@ private void createOutputProcedure2() throws SQLException { private void testOutputProcedure2RandomOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -934,18 +897,12 @@ private void testOutputProcedure2RandomOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure2Inorder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -993,18 +950,12 @@ private void testOutputProcedure2Inorder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure2ReverseOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -1053,11 +1004,6 @@ private void testOutputProcedure2ReverseOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure() throws SQLException { @@ -1076,8 +1022,7 @@ private void createOutputProcedure() throws SQLException { private void testOutputProcedureRandomOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1121,18 +1066,12 @@ private void testOutputProcedureRandomOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureInorder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1169,18 +1108,12 @@ private void testOutputProcedureInorder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureReverseOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1216,11 +1149,6 @@ private void testOutputProcedureReverseOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createInOutProcedure() throws SQLException { @@ -1236,8 +1164,7 @@ private void createInOutProcedure() throws SQLException { private void testInOutProcedure(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(numericValues[3])); callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1250,11 +1177,6 @@ private void testInOutProcedure(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure() throws SQLException { @@ -1271,8 +1193,7 @@ private void createMixedProcedure() throws SQLException { private void testMixedProcedure(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.setInt(2, Integer.parseInt(numericValues[3])); @@ -1296,11 +1217,6 @@ private void testMixedProcedure(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure2() throws SQLException { @@ -1317,8 +1233,7 @@ private void createMixedProcedure2() throws SQLException { private void testMixedProcedure2RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1348,17 +1263,11 @@ private void testMixedProcedure2RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure2Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1375,11 +1284,6 @@ private void testMixedProcedure2Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure3() throws SQLException { @@ -1395,8 +1299,7 @@ private void createMixedProcedure3() throws SQLException { private void testMixedProcedure3RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1426,17 +1329,11 @@ private void testMixedProcedure3RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure3Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1453,17 +1350,11 @@ private void testMixedProcedure3Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1480,11 +1371,6 @@ private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedureNumericPrcisionScale() throws SQLException { @@ -1503,8 +1389,7 @@ private void createMixedProcedureNumericPrcisionScale() throws SQLException { private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQLException { - try { - SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter(2, java.sql.Types.DECIMAL, 10, 5); @@ -1530,17 +1415,11 @@ private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQ catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) throws SQLException { - try { - SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter("p1", java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter("p2", java.sql.Types.DECIMAL, 10, 5); @@ -1566,11 +1445,6 @@ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) thr catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureChar() throws SQLException { @@ -1589,7 +1463,7 @@ private void createOutputProcedureChar() throws SQLException { private void testOutputProcedureCharInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1632,16 +1506,11 @@ private void testOutputProcedureCharInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureCharInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1687,11 +1556,6 @@ private void testOutputProcedureCharInorderObject(String sql) throws SQLExceptio catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureNumeric() throws SQLException { @@ -1788,11 +1652,6 @@ private void testOutputProcedureNumericInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLException { @@ -2009,11 +1868,6 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private Object createValue(Class coercion, @@ -2037,7 +1891,6 @@ private Object createValue(Class coercion, return new BigDecimal(numericValues[index]); } catch (java.lang.NumberFormatException e) { - return null; } return null; } @@ -2156,11 +2009,6 @@ private void testOutputProcedureBinaryInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureBinaryInorderObject(String sql) throws SQLException { @@ -2199,11 +2047,6 @@ private void testOutputProcedureBinaryInorderObject(String sql) throws SQLExcept catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureBinaryInorderString(String sql) throws SQLException { @@ -2217,37 +2060,30 @@ private void testOutputProcedureBinaryInorderString(String sql) throws SQLExcept callableStatement.execute(); int index = 1; - try { - for (int i = 0; i < byteValues.size(); i++) { - String stringValue1 = ("" + callableStatement.getString(index)).trim(); + for (int i = 0; i < byteValues.size(); i++) { + String stringValue1 = ("" + callableStatement.getString(index)).trim(); - StringBuffer expected = new StringBuffer(); - String expectedStr = null; + StringBuffer expected = new StringBuffer(); + String expectedStr = null; - if (null != byteValues.get(i)) { - for (byte b : byteValues.get(i)) { - expected.append(String.format("%02X", b)); - } - expectedStr = "" + expected.toString(); - } - else { - expectedStr = "null"; - } - try { - assertEquals(stringValue1.startsWith(expectedStr), true, - "\nDecryption failed with getString(): " + stringValue1 + ".\nExpected Value: " + expectedStr); - } - catch (Exception e) { - fail(e.toString()); - } - finally { - index++; + if (null != byteValues.get(i)) { + for (byte b : byteValues.get(i)) { + expected.append(String.format("%02X", b)); } + expectedStr = "" + expected.toString(); } - } - finally { - if (null != callableStatement) { - callableStatement.close(); + else { + expectedStr = "null"; + } + try { + assertEquals(stringValue1.startsWith(expectedStr), true, + "\nDecryption failed with getString(): " + stringValue1 + ".\nExpected Value: " + expectedStr); + } + catch (Exception e) { + fail(e.toString()); + } + finally { + index++; } } } @@ -2419,7 +2255,7 @@ private void createOutputProcedureDate() throws SQLException { private void testOutputProcedureDateInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2459,16 +2295,11 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureDateInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2508,11 +2339,6 @@ private void testOutputProcedureDateInorderObject(String sql) throws SQLExceptio catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureBatch() throws SQLException { @@ -2531,8 +2357,7 @@ private void createOutputProcedureBatch() throws SQLException { private void testOutputProcedureBatchInorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -2555,11 +2380,6 @@ private void testOutputProcedureBatchInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure4() throws SQLException { @@ -2614,11 +2434,6 @@ private void testMixedProcedureDateScaleInorder(String sql) throws SQLException catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQLException { @@ -2645,10 +2460,5 @@ private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQL catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } } From 5b2657c7e3001a453773eb1fb071cce46213a8cc Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Mon, 2 Oct 2017 15:51:25 -0700 Subject: [PATCH 31/68] Update .travis.yml Updated docker image tag for mssql-server-linux --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3c90e82b0..3c19a2b8f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,7 +33,7 @@ install: - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -Pbuild42 before_script: - - docker pull microsoft/mssql-server-linux + - docker pull microsoft/mssql-server-linux:2017-latest - docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=' -p 1433:1433 -d microsoft/mssql-server-linux script: From 2bb154a220778380b74c8dc120991ae137e90cb1 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Mon, 2 Oct 2017 15:58:13 -0700 Subject: [PATCH 32/68] Updating travis build script to use :2017-latest tag for SQL Server docker image --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3c90e82b0..3c19a2b8f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,7 +33,7 @@ install: - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -Pbuild42 before_script: - - docker pull microsoft/mssql-server-linux + - docker pull microsoft/mssql-server-linux:2017-latest - docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=' -p 1433:1433 -d microsoft/mssql-server-linux script: From 7efd39ffc39f735154ce372ebe79281410e7e747 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Mon, 2 Oct 2017 16:02:02 -0700 Subject: [PATCH 33/68] Update .travis.yml Updating docker run command as well. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3c19a2b8f..47c919414 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,7 +34,7 @@ install: before_script: - docker pull microsoft/mssql-server-linux:2017-latest - - docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=' -p 1433:1433 -d microsoft/mssql-server-linux + - docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=' -p 1433:1433 -d microsoft/mssql-server-linux:2017-latest script: - docker ps -a From d15c84def18b30362ac25c7a3e4e35a98c881182 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Mon, 2 Oct 2017 16:03:50 -0700 Subject: [PATCH 34/68] Update docker run command as well --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3c19a2b8f..47c919414 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,7 +34,7 @@ install: before_script: - docker pull microsoft/mssql-server-linux:2017-latest - - docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=' -p 1433:1433 -d microsoft/mssql-server-linux + - docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=' -p 1433:1433 -d microsoft/mssql-server-linux:2017-latest script: - docker ps -a From 052b4b5410a39f7dffb8eebe454e4f1d1703f6a9 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Mon, 2 Oct 2017 17:25:35 -0700 Subject: [PATCH 35/68] Fix AESetup issue with dropCEK --- .../sqlserver/jdbc/AlwaysEncrypted/AESetup.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java index bfacd630b..9ae2445c1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -96,8 +96,8 @@ static void setUpConnection() throws TestAbortedException, Exception { try(SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { - dropCEK(); - dropCMK(); + dropCEK(stmt); + dropCMK(stmt); } keyPath = Utils.getCurrentClassPath() + jksName; @@ -126,8 +126,8 @@ static void setUpConnection() throws TestAbortedException, Exception { @AfterAll private static void dropAll() throws SQLServerException, SQLException { dropTables(stmt); - dropCEK(); - dropCMK(); + dropCEK(stmt); + dropCMK(stmt); Util.close(null, stmt, con); } @@ -2062,7 +2062,7 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S * @throws SQLServerException * @throws SQLException */ - private static void dropCEK() throws SQLServerException, SQLException { + private static void dropCEK(SQLServerStatement stmt) throws SQLServerException, SQLException { String cekSql = " if exists (SELECT name from sys.column_encryption_keys where name='" + cekName + "')" + " begin" + " drop column encryption key " + cekName + " end"; stmt.execute(cekSql); @@ -2074,7 +2074,7 @@ private static void dropCEK() throws SQLServerException, SQLException { * @throws SQLServerException * @throws SQLException */ - private static void dropCMK() throws SQLServerException, SQLException { + private static void dropCMK(SQLServerStatement stmt) throws SQLServerException, SQLException { String cekSql = " if exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')" + " begin" + " drop column master key " + cmkName + " end"; stmt.execute(cekSql); From 5ef8dea079dc00fd930af86bea53c642ac585df7 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Tue, 3 Oct 2017 16:20:38 -0700 Subject: [PATCH 36/68] try-with-resources implementation commit 2 --- .../JDBCEncryptionDecryptionTest.java | 113 ++--- .../AlwaysEncrypted/PrecisionScaleTest.java | 422 +++++++++--------- .../jdbc/bulkCopy/BulkCopyAllTypes.java | 72 ++- .../jdbc/bulkCopy/BulkCopyCSVTest.java | 133 +++--- .../bulkCopy/BulkCopyColumnMappingTest.java | 51 +-- .../jdbc/bulkCopy/BulkCopyConnectionTest.java | 23 +- .../BulkCopyISQLServerBulkRecordTest.java | 45 +- .../bulkCopy/BulkCopyResultSetCursorTest.java | 257 +++++------ .../jdbc/bulkCopy/BulkCopyTestSetUp.java | 31 +- .../jdbc/bulkCopy/BulkCopyTestUtil.java | 417 ++++++++--------- .../jdbc/bulkCopy/BulkCopyTimeoutTest.java | 26 +- .../ISQLServerBulkRecordIssuesTest.java | 61 ++- .../microsoft/sqlserver/jdbc/bvt/bvtTest.java | 314 ++++--------- .../sqlserver/jdbc/bvt/bvtTestSetup.java | 17 +- .../CallableStatementTest.java | 54 +-- .../jdbc/connection/ConnectionDriverTest.java | 160 ++++--- .../jdbc/connection/DBMetadataTest.java | 35 +- .../connection/NativeMSSQLDataSourceTest.java | 49 +- .../jdbc/connection/PoolingTest.java | 28 +- .../sqlserver/testframework/DBConnection.java | 2 +- .../sqlserver/testframework/DBResultSet.java | 2 +- .../sqlserver/testframework/DBStatement.java | 4 +- 22 files changed, 981 insertions(+), 1335 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java index 0c1de2266..06e44276b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java @@ -512,68 +512,46 @@ public void testNumericNormalization() throws SQLException { private void testChar(SQLServerStatement stmt, String[] values) throws SQLException { String sql = "select * from " + charTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetString(rs, numberOfColumns, values); + testGetObject(rs, numberOfColumns, values); + } + } } - else { - rs = stmt.executeQuery(sql); - } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, values); - testGetObject(rs, numberOfColumns, values); - } - - Util.close(rs, pstmt, null); } private void testBinary(SQLServerStatement stmt, LinkedList values) throws SQLException { String sql = "select * from " + binaryTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); - } - else { - rs = stmt.executeQuery(sql); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetStringForBinary(rs, numberOfColumns, values); + testGetBytes(rs, numberOfColumns, values); + testGetObjectForBinary(rs, numberOfColumns, values); + } + } } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetStringForBinary(rs, numberOfColumns, values); - testGetBytes(rs, numberOfColumns, values); - testGetObjectForBinary(rs, numberOfColumns, values); - } - - Util.close(rs, pstmt, null); } private void testDate(SQLServerStatement stmt, LinkedList values1) throws SQLException { - String sql = "select * from " + dateTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + // testGetStringForDate(rs, numberOfColumns, values1); //TODO: Disabling, since getString throws verification error for zero temporal + // types + testGetObjectForTemporal(rs, numberOfColumns, values1); + testGetDate(rs, numberOfColumns, values1); + } + } } - else { - rs = stmt.executeQuery(sql); - } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - // testGetStringForDate(rs, numberOfColumns, values1); //TODO: Disabling, since getString throws verification error for zero temporal - // types - testGetObjectForTemporal(rs, numberOfColumns, values1); - testGetDate(rs, numberOfColumns, values1); - } - - Util.close(rs, pstmt, null); } private void testGetObject(ResultSet rs, @@ -948,29 +926,22 @@ private void testNumeric(Statement stmt, String[] numericValues, boolean isNull) throws SQLException { String sql = "select * from " + numericTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - SQLServerResultSet rs = null; - if (stmt == null) { - rs = (SQLServerResultSet) pstmt.executeQuery(); - } - else { - rs = (SQLServerResultSet) stmt.executeQuery(sql); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(SQLServerResultSet rs = (stmt == null) ? (SQLServerResultSet) pstmt.executeQuery() : (SQLServerResultSet) stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetString(rs, numberOfColumns, numericValues); + testGetObject(rs, numberOfColumns, numericValues); + testGetBigDecimal(rs, numberOfColumns, numericValues); + if (!isNull) + testWithSpecifiedtype(rs, numberOfColumns, numericValues); + else { + String[] nullNumericValues = {"false", "0", "0", "0", "0", "0.0", "0.0", "0.0", null, null, null, null, null, null, null, null}; + testWithSpecifiedtype(rs, numberOfColumns, nullNumericValues); + } + } + } } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, numericValues); - testGetObject(rs, numberOfColumns, numericValues); - testGetBigDecimal(rs, numberOfColumns, numericValues); - if (!isNull) - testWithSpecifiedtype(rs, numberOfColumns, numericValues); - else { - String[] nullNumericValues = {"false", "0", "0", "0", "0", "0.0", "0.0", "0.0", null, null, null, null, null, null, null, null}; - testWithSpecifiedtype(rs, numberOfColumns, nullNumericValues); - } - } - - Util.close(rs, pstmt, null); } private void testWithSpecifiedtype(SQLServerResultSet rs, diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java index 23dede74d..4d7b8b3d0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -155,38 +155,32 @@ public void testDateScale5Null() throws Exception { private void testNumeric(String[] numeric) throws SQLException { - ResultSet rs = stmt.executeQuery("select * from " + numericTable); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - ArrayList skipMax = new ArrayList<>(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, skipMax, numeric); - testGetBigDecimal(rs, numberOfColumns, numeric); - testGetObject(rs, numberOfColumns, skipMax, numeric); - } - - if (null != rs) { - rs.close(); + try(ResultSet rs = stmt.executeQuery("select * from " + numericTable)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + ArrayList skipMax = new ArrayList<>(); + + while (rs.next()) { + testGetString(rs, numberOfColumns, skipMax, numeric); + testGetBigDecimal(rs, numberOfColumns, numeric); + testGetObject(rs, numberOfColumns, skipMax, numeric); + } } } private void testDate(String[] dateNormalCase, String[] dateSetObject) throws Exception { - ResultSet rs = stmt.executeQuery("select * from " + dateTable); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - ArrayList skipMax = new ArrayList<>(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, skipMax, dateNormalCase); - testGetObject(rs, numberOfColumns, skipMax, dateSetObject); - testGetDate(rs, numberOfColumns, dateSetObject); - } - - if (null != rs) { - rs.close(); + try(ResultSet rs = stmt.executeQuery("select * from " + dateTable)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + ArrayList skipMax = new ArrayList<>(); + + while (rs.next()) { + testGetString(rs, numberOfColumns, skipMax, dateNormalCase); + testGetObject(rs, numberOfColumns, skipMax, dateSetObject); + testGetDate(rs, numberOfColumns, dateSetObject); + } } } @@ -351,79 +345,79 @@ private void testGetDate(ResultSet rs, private void populateDateNormalCase(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, new Timestamp(date.getTime()), scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, new Timestamp(date.getTime())); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1)); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, new Time(date.getTime())); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setTime(i, new Time(date.getTime()), scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, new Timestamp(date.getTime()), scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, new Timestamp(date.getTime())); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1)); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, new Time(date.getTime())); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setTime(i, new Time(date.getTime()), scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), scale); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateNormalCaseNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, null, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, null); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, null); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, null); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setTime(i, null, scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, null, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, null); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, null); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, null); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setTime(i, null, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setDateTimeOffset(i, null, scale); + } + + pstmt.execute(); } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setDateTimeOffset(i, null, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericNormalCase(String[] numeric, @@ -431,25 +425,25 @@ private void populateNumericNormalCase(String[] numeric, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setDouble(i, Double.valueOf(numeric[0])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setDouble(i, Double.valueOf(numeric[0])); + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numeric[1]), precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numeric[2]), precision, scale); + } + + pstmt.execute(); } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numeric[1]), precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numeric[2]), precision, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericSetObject(String[] numeric, @@ -457,129 +451,129 @@ private void populateNumericSetObject(String[] numeric, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, Double.valueOf(numeric[0])); - - } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, new BigDecimal(numeric[1]), java.sql.Types.DECIMAL, precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, new BigDecimal(numeric[2]), java.sql.Types.NUMERIC, precision, scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, Double.valueOf(numeric[0])); + + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, new BigDecimal(numeric[1]), java.sql.Types.DECIMAL, precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, new BigDecimal(numeric[2]), java.sql.Types.NUMERIC, precision, scale); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericSetObjectNull(int precision, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); - + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, precision, scale); + } + + pstmt.execute(); } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, precision, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateSetObject(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET, scale); + } + + pstmt.execute(); } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME, scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateSetObjectNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET, scale); + } + + pstmt.execute(); } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME, scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java index d97726b27..7782a86b7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java @@ -27,9 +27,7 @@ @RunWith(JUnitPlatform.class) public class BulkCopyAllTypes extends AbstractTest { - private static Connection conn = null; - static Statement stmt = null; - + private static DBTable tableSrc = null; private static DBTable tableDest = null; @@ -53,55 +51,43 @@ private void testBulkCopyResultSet(boolean setSelectMethod, Integer resultSetConcurrency) throws SQLException { setupVariation(); - Connection connnection = null; - if (setSelectMethod) { - connnection = DriverManager.getConnection(connectionString + ";selectMethod=cursor;"); - } - else { - connnection = DriverManager.getConnection(connectionString); - } - - Statement stmtement = null; - if (null != resultSetType || null != resultSetConcurrency) { - stmtement = connnection.createStatement(resultSetType, resultSetConcurrency); + try(Connection connnection = DriverManager.getConnection(connectionString + (setSelectMethod ? ";selectMethod=cursor;" : "")); + Statement statement = (null != resultSetType || null != resultSetConcurrency) ? + connnection.createStatement(resultSetType, resultSetConcurrency) : connnection.createStatement()){ + + ResultSet rs = statement.executeQuery("select * from " + tableSrc.getEscapedTableName()); + + SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); + bcOperation.setDestinationTableName(tableDest.getEscapedTableName()); + bcOperation.writeToServer(rs); + bcOperation.close(); + + ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, tableDest); } - else { - stmtement = connnection.createStatement(); - } - - ResultSet rs = stmtement.executeQuery("select * from " + tableSrc.getEscapedTableName()); - - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); - bcOperation.setDestinationTableName(tableDest.getEscapedTableName()); - bcOperation.writeToServer(rs); - bcOperation.close(); - - ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, tableDest); terminateVariation(); } private void setupVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - - DBConnection dbConnection = new DBConnection(connectionString); - DBStatement dbStmt = dbConnection.createStatement(); - - tableSrc = new DBTable(true); - tableDest = tableSrc.cloneSchema(); - - dbStmt.createTable(tableSrc); - dbStmt.createTable(tableDest); - - dbStmt.populateTable(tableSrc); + try(DBConnection dbConnection = new DBConnection(connectionString); + DBStatement dbStmt = dbConnection.createStatement()) { + + tableSrc = new DBTable(true); + tableDest = tableSrc.cloneSchema(); + + dbStmt.createTable(tableSrc); + dbStmt.createTable(tableDest); + + dbStmt.populateTable(tableSrc); + } } private void terminateVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); + try(Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { - Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); - Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); + Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + } } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java index c915ad594..ebf311225 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java @@ -77,9 +77,7 @@ static void setUpConnection() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord") void testCSV() { - SQLServerBulkCSVFileRecord fileRecord; - try { - fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, encoding, delimiter, true); + try (SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, encoding, delimiter, true)) { testBulkCopyCSV(fileRecord, true); } catch (SQLServerException e) { @@ -93,9 +91,7 @@ void testCSV() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord First line not being column name") void testCSVFirstLineNotColumnName() { - SQLServerBulkCSVFileRecord fileRecord; - try { - fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFileNoColumnName, encoding, delimiter, false); + try (SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFileNoColumnName, encoding, delimiter, false)) { testBulkCopyCSV(fileRecord, false); } catch (SQLServerException e) { @@ -111,10 +107,9 @@ void testCSVFirstLineNotColumnName() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord with passing file from url") void testCSVFromURL() throws SQLException { - try { - InputStream csvFileInputStream = new URL( + try (InputStream csvFileInputStream = new URL( "https://raw.githubusercontent.com/Microsoft/mssql-jdbc/master/src/test/resources/BulkCopyCSVTestInput.csv").openStream(); - SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(csvFileInputStream, encoding, delimiter, true); + SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(csvFileInputStream, encoding, delimiter, true)) { testBulkCopyCSV(fileRecord, true); } catch (Exception e) { @@ -125,53 +120,52 @@ void testCSVFromURL() throws SQLException { private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, boolean firstLineIsColumnNames) { DBTable destTable = null; - try { - BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding)); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { // read the first line from csv and parse it to get datatypes to create destination column String[] columnTypes = br.readLine().substring(1)/* Skip the Byte order mark */.split(delimiter, -1); br.close(); int numberOfColumns = columnTypes.length; destTable = new DBTable(false); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - bulkCopy.setDestinationTableName(destTable.getEscapedTableName()); - - // add a column in destTable for each datatype in csv - for (int i = 0; i < numberOfColumns; i++) { - SqlType sqlType = null; - int precision = -1; - int scale = -1; - - String columnType = columnTypes[i].trim().toLowerCase(); - int indexOpenParenthesis = columnType.lastIndexOf("("); - // skip the parenthesis in case of precision and scale type - if (-1 != indexOpenParenthesis) { - String precision_scale = columnType.substring(indexOpenParenthesis + 1, columnType.length() - 1); - columnType = columnType.substring(0, indexOpenParenthesis); - sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; - - // add scale if exist - int indexPrecisionScaleSeparator = precision_scale.indexOf("-"); - if (-1 != indexPrecisionScaleSeparator) { - scale = Integer.parseInt(precision_scale.substring(indexPrecisionScaleSeparator + 1)); - sqlType.setScale(scale); - precision_scale = precision_scale.substring(0, indexPrecisionScaleSeparator); - } - // add precision - precision = Integer.parseInt(precision_scale); - sqlType.setPrecision(precision); - } - else { - sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; - } - - destTable.addColumn(sqlType); - fileRecord.addColumnMetadata(i + 1, "", sqlType.getJdbctype().getVendorTypeNumber(), (-1 == precision) ? 0 : precision, - (-1 == scale) ? 0 : scale); + try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy((Connection) con.product())) { + bulkCopy.setDestinationTableName(destTable.getEscapedTableName()); + + // add a column in destTable for each datatype in csv + for (int i = 0; i < numberOfColumns; i++) { + SqlType sqlType = null; + int precision = -1; + int scale = -1; + + String columnType = columnTypes[i].trim().toLowerCase(); + int indexOpenParenthesis = columnType.lastIndexOf("("); + // skip the parenthesis in case of precision and scale type + if (-1 != indexOpenParenthesis) { + String precision_scale = columnType.substring(indexOpenParenthesis + 1, columnType.length() - 1); + columnType = columnType.substring(0, indexOpenParenthesis); + sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; + + // add scale if exist + int indexPrecisionScaleSeparator = precision_scale.indexOf("-"); + if (-1 != indexPrecisionScaleSeparator) { + scale = Integer.parseInt(precision_scale.substring(indexPrecisionScaleSeparator + 1)); + sqlType.setScale(scale); + precision_scale = precision_scale.substring(0, indexPrecisionScaleSeparator); + } + // add precision + precision = Integer.parseInt(precision_scale); + sqlType.setPrecision(precision); + } + else { + sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; + } + + destTable.addColumn(sqlType); + fileRecord.addColumnMetadata(i + 1, "", sqlType.getJdbctype().getVendorTypeNumber(), (-1 == precision) ? 0 : precision, + (-1 == scale) ? 0 : scale); + } + stmt.createTable(destTable); + bulkCopy.writeToServer((ISQLServerBulkRecord) fileRecord); } - stmt.createTable(destTable); - bulkCopy.writeToServer((ISQLServerBulkRecord) fileRecord); - bulkCopy.close(); if (firstLineIsColumnNames) validateValuesFromCSV(destTable, inputFile); else @@ -186,7 +180,6 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, stmt.dropTable(destTable); } } - } /** @@ -196,30 +189,28 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, */ static void validateValuesFromCSV(DBTable destinationTable, String inputFile) { - BufferedReader br; - try { - br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding)); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { if (inputFile.equalsIgnoreCase("BulkCopyCSVTestInput.csv")) br.readLine(); // skip first line as it is header - DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - while (dstResultSet.next()) { - String[] srcValues = br.readLine().split(delimiter); - if ((0 == srcValues.length) && (srcValues.length != totalColumns)) { - srcValues = new String[totalColumns]; - Arrays.fill(srcValues, null); - } - for (int i = 1; i <= totalColumns; i++) { - String srcValue = srcValues[i - 1]; - String dstValue = dstResultSet.getString(i); - srcValue = (null != srcValue) ? srcValue.trim() : srcValue; - dstValue = (null != dstValue) ? dstValue.trim() : dstValue; - - // get the value from csv as string and compare them - ComparisonUtil.compareExpectedAndActual(java.sql.Types.VARCHAR, srcValue, dstValue); - } + try (DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + while (dstResultSet.next()) { + String[] srcValues = br.readLine().split(delimiter); + if ((0 == srcValues.length) && (srcValues.length != totalColumns)) { + srcValues = new String[totalColumns]; + Arrays.fill(srcValues, null); + } + for (int i = 1; i <= totalColumns; i++) { + String srcValue = srcValues[i - 1]; + String dstValue = dstResultSet.getString(i); + srcValue = (null != srcValue) ? srcValue.trim() : srcValue; + dstValue = (null != dstValue) ? dstValue.trim() : dstValue; + // get the value from csv as string and compare them + ComparisonUtil.compareExpectedAndActual(java.sql.Types.VARCHAR, srcValue, dstValue); + } + } } } catch (Exception e) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java index 22570060a..2de49b360 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -332,31 +332,32 @@ void testInvalidCM() { private void validateValuesRepetativeCM(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { - DBStatement srcStmt = con.createStatement(); - DBStatement dstStmt = con.createStatement(); - DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData sourceMeta = ((ResultSet) srcResultSet.product()).getMetaData(); - int totalColumns = sourceMeta.getColumnCount(); - - // verify data from sourceType and resultSet - while (srcResultSet.next() && dstResultSet.next()) - for (int i = 1; i <= totalColumns; i++) { - // TODO: check row and column count in both the tables - - Object srcValue, dstValue; - srcValue = srcResultSet.getObject(i); - dstValue = dstResultSet.getObject(i); - ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValue, dstValue); - - // compare value of first column of source with extra column in destination - if (1 == i) { - Object srcValueFirstCol = srcResultSet.getObject(i); - Object dstValLastCol = dstResultSet.getObject(totalColumns + 1); - ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValueFirstCol, dstValLastCol); - } - } - + try(DBStatement srcStmt = con.createStatement(); + DBStatement dstStmt = con.createStatement(); + DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData sourceMeta = ((ResultSet) srcResultSet.product()).getMetaData(); + int totalColumns = sourceMeta.getColumnCount(); + + // verify data from sourceType and resultSet + while (srcResultSet.next() && dstResultSet.next()) { + for (int i = 1; i <= totalColumns; i++) { + // TODO: check row and column count in both the tables + + Object srcValue, dstValue; + srcValue = srcResultSet.getObject(i); + dstValue = dstResultSet.getObject(i); + ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValue, dstValue); + + // compare value of first column of source with extra column in destination + if (1 == i) { + Object srcValueFirstCol = srcResultSet.getObject(i); + Object dstValLastCol = dstResultSet.getObject(totalColumns + 1); + ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValueFirstCol, dstValLastCol); + } + } + } + } } private void dropTable(String tableName) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java index 340dbb3eb..f56039813 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java @@ -12,6 +12,7 @@ import java.lang.reflect.Method; import java.sql.Connection; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; @@ -88,9 +89,11 @@ public void execute() { void testInvalidConnection1() { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override - public void execute() throws SQLServerException { - Connection con = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + public void execute() throws SQLException { + try(Connection con = null; + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con)) { + //do nothing + } } }); } @@ -104,8 +107,10 @@ void testInvalidConnection2() { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override public void execute() throws SQLServerException { - SQLServerConnection con = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + try(SQLServerConnection con = null; + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con)) { + //do nothing + } } }); } @@ -120,7 +125,9 @@ void testInvalidConnection3() { @Override public void execute() throws SQLServerException { String connectionUrl = " "; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl); + try(SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl)) { + //do nothing + } } }); } @@ -135,7 +142,9 @@ void testInvalidConnection4() { @Override public void execute() throws SQLServerException { String connectionUrl = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl); + try(SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl)) { + //do nothing + } } }); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java index 60e7e3da4..1be4ad850 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java @@ -38,39 +38,18 @@ @DisplayName("Test ISQLServerBulkRecord") public class BulkCopyISQLServerBulkRecordTest extends AbstractTest { - static DBConnection con = null; - static DBStatement stmt = null; - static DBTable dstTable = null; - - /** - * Create connection and statement - */ - @BeforeAll - static void setUpConnection() { - con = new DBConnection(connectionString); - stmt = con.createStatement(); - } - @Test - void testISQLServerBulkRecord() { - dstTable = new DBTable(true); - stmt.createTable(dstTable); - BulkData Bdata = new BulkData(); - - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, Bdata, dstTable); - } - - /** - * drop source table after testing bulk copy - * - * @throws SQLException - */ - @AfterAll - static void tearConnection() throws SQLException { - stmt.close(); - con.close(); + void testISQLServerBulkRecord() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement()) { + DBTable dstTable = new DBTable(true); + stmt.createTable(dstTable); + BulkData Bdata = new BulkData(dstTable); + + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, Bdata, dstTable); + } } class BulkData implements ISQLServerBulkRecord { @@ -98,7 +77,7 @@ private class ColumnMetadata { Map columnMetadata; List data; - BulkData() { + BulkData(DBTable dstTable) { columnMetadata = new HashMap<>(); totalColumn = dstTable.totalColumns(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java index eeaad7577..774deff4a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -20,7 +20,6 @@ import java.util.Properties; import java.util.TimeZone; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -33,9 +32,6 @@ @RunWith(JUnitPlatform.class) public class BulkCopyResultSetCursorTest extends AbstractTest { - private static Connection conn = null; - static Statement stmt = null; - static BigDecimal[] expectedBigDecimals = {new BigDecimal("12345.12345"), new BigDecimal("125.123"), new BigDecimal("45.12345")}; static String[] expectedBigDecimalStrings = {"12345.12345", "125.12300", "45.12345"}; @@ -62,27 +58,20 @@ public void testServerCursors() throws SQLException { private void serverCursorsTest(int resultSetType, int resultSetConcurrency) throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - - verifyDestinationTableData(expectedBigDecimals.length); - - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != rs) { - rs.close(); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency).executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -95,28 +84,19 @@ private void serverCursorsTest(int resultSetType, public void testSelectMethodSetToCursor() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - conn = DriverManager.getConnection(connectionString, info); - - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - - verifyDestinationTableData(expectedBigDecimals.length); - - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != rs) { - rs.close(); + try (Connection conn = DriverManager.getConnection(connectionString, info); + Statement stmt = conn.createStatement()) { + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -127,133 +107,106 @@ public void testSelectMethodSetToCursor() throws SQLException { */ @Test public void testMultiplePreparedStatementAndResultSet() throws SQLException { - conn = DriverManager.getConnection(connectionString); - - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length); - - rs.beforeFirst(); - SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn); - bulkCopy1.setDestinationTableName(desTable); - bulkCopy1.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length * 2); - - rs.beforeFirst(); - SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn); - bulkCopy2.setDestinationTableName(desTable); - bulkCopy2.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length * 3); - - String sql = "insert into " + desTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql); - for (int i = 0; i < expectedBigDecimals.length; i++) { - pstmt1.setBigDecimal(1, expectedBigDecimals[i]); - pstmt1.setString(2, expectedStrings[i]); - pstmt1.setTimestamp(3, expectedTimestamps[i], calGMT); - pstmt1.setString(4, expectedStrings[i]); - pstmt1.execute(); - } - verifyDestinationTableData(expectedBigDecimals.length * 4); - - ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn); - bulkCopy3.setDestinationTableName(desTable); - bulkCopy3.writeToServer(rs2); - verifyDestinationTableData(expectedBigDecimals.length * 5); - - if (null != pstmt1) { - pstmt1.close(); - } - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != bulkCopy1) { - bulkCopy1.close(); - } - if (null != bulkCopy2) { - bulkCopy2.close(); - } - if (null != bulkCopy3) { - bulkCopy3.close(); - } - if (null != rs) { - rs.close(); - } - if (null != rs2) { - rs2.close(); - } + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable)) { + try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length); + } + + rs.beforeFirst(); + try (SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn)) { + bulkCopy1.setDestinationTableName(desTable); + bulkCopy1.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length * 2); + } + + rs.beforeFirst(); + try (SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn)) { + bulkCopy2.setDestinationTableName(desTable); + bulkCopy2.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length * 3); + } + + String sql = "insert into " + desTable + " values (?,?,?,?)"; + Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + try (SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { + for (int i = 0; i < expectedBigDecimals.length; i++) { + pstmt1.setBigDecimal(1, expectedBigDecimals[i]); + pstmt1.setString(2, expectedStrings[i]); + pstmt1.setTimestamp(3, expectedTimestamps[i], calGMT); + pstmt1.setString(4, expectedStrings[i]); + pstmt1.execute(); + } + verifyDestinationTableData(expectedBigDecimals.length * 4); + } + try (ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn)) { + bulkCopy3.setDestinationTableName(desTable); + bulkCopy3.writeToServer(rs2); + verifyDestinationTableData(expectedBigDecimals.length * 5); + } + } + } } private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { - ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable); - - int expectedArrayLength = expectedBigDecimals.length; - - int i = 0; - while (rs.next()) { - assertTrue(rs.getString(1).equals(expectedBigDecimalStrings[i % expectedArrayLength]), - "Expected Value:" + expectedBigDecimalStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(1)); - assertTrue(rs.getString(2).trim().equals(expectedStrings[i % expectedArrayLength]), - "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(2)); - assertTrue(rs.getString(3).equals(expectedTimestampStrings[i % expectedArrayLength]), - "Expected Value:" + expectedTimestampStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(3)); - assertTrue(rs.getString(4).trim().equals(expectedStrings[i % expectedArrayLength]), - "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(4)); - i++; + try (Connection conn = DriverManager.getConnection(connectionString); + ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + + int expectedArrayLength = expectedBigDecimals.length; + + int i = 0; + while (rs.next()) { + assertTrue(rs.getString(1).equals(expectedBigDecimalStrings[i % expectedArrayLength]), + "Expected Value:" + expectedBigDecimalStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(1)); + assertTrue(rs.getString(2).trim().equals(expectedStrings[i % expectedArrayLength]), + "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(2)); + assertTrue(rs.getString(3).equals(expectedTimestampStrings[i % expectedArrayLength]), + "Expected Value:" + expectedTimestampStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(3)); + assertTrue(rs.getString(4).trim().equals(expectedStrings[i % expectedArrayLength]), + "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(4)); + i++; + } + + assertTrue(i == expectedNumberOfRows); } - - assertTrue(i == expectedNumberOfRows); } private static void populateSourceTable() throws SQLException { String sql = "insert into " + srcTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql); + try (Connection conn = DriverManager.getConnection(connectionString); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { - for (int i = 0; i < expectedBigDecimals.length; i++) { - pstmt.setBigDecimal(1, expectedBigDecimals[i]); - pstmt.setString(2, expectedStrings[i]); - pstmt.setTimestamp(3, expectedTimestamps[i], calGMT); - pstmt.setString(4, expectedStrings[i]); - pstmt.execute(); + for (int i = 0; i < expectedBigDecimals.length; i++) { + pstmt.setBigDecimal(1, expectedBigDecimals[i]); + pstmt.setString(2, expectedStrings[i]); + pstmt.setTimestamp(3, expectedTimestamps[i], calGMT); + pstmt.setString(4, expectedStrings[i]); + pstmt.execute(); + } } } - private static void dropTables() throws SQLException { + private static void dropTables(Statement stmt) throws SQLException { Utils.dropTableIfExists(srcTable, stmt); Utils.dropTableIfExists(desTable, stmt); } - private static void createTables() throws SQLException { + private static void createTables(Statement stmt) throws SQLException { String sql = "create table " + srcTable + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); sql = "create table " + desTable + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } - - @AfterEach - private void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java index 2b23bf836..f916336de 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java @@ -7,6 +7,8 @@ */ package com.microsoft.sqlserver.jdbc.bulkCopy; +import java.sql.SQLException; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.platform.runner.JUnitPlatform; @@ -28,39 +30,28 @@ public class BulkCopyTestSetUp extends AbstractTest { /** * Create source table needed for testing bulk copy + * @throws SQLException */ @BeforeAll - static void setUpSourceTable() { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(connectionString); - stmt = con.createStatement(); + static void setUpSourceTable() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement(); + DBPreparedStatement pstmt = new DBPreparedStatement(con);) { sourceTable = new DBTable(true); stmt.createTable(sourceTable); - DBPreparedStatement pstmt = new DBPreparedStatement(con); pstmt.populateTable(sourceTable); } - finally { - con.close(); - } } /** * drop source table after testing bulk copy + * @throws SQLException */ @AfterAll - static void dropSourceTable() { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(connectionString); - stmt = con.createStatement(); + static void dropSourceTable() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement()) { stmt.dropTable(sourceTable); } - finally { - con.close(); - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java index fd51ef544..0b902587e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java @@ -7,20 +7,12 @@ */ package com.microsoft.sqlserver.jdbc.bulkCopy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.math.BigDecimal; import java.sql.Connection; -import java.sql.Date; -import java.sql.JDBCType; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; -import java.sql.Time; -import java.sql.Timestamp; - import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.bulkCopy.BulkCopyTestWrapper.ColumnMap; @@ -28,7 +20,6 @@ import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.ComparisonUtil; /** @@ -70,57 +61,53 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, boolean validateResult) { - DBConnection con = null; - DBStatement stmt = null; DBTable destinationTable = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement()) { destinationTable = sourceTable.cloneSchema(); stmt.createTable(destinationTable); - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); + try (DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } + catch (SQLException ex) { + fail(ex.getMessage()); } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); + finally { + stmt.dropTable(destinationTable); + con.close(); } } catch (SQLException ex) { fail(ex.getMessage()); } - finally { - stmt.dropTable(destinationTable); - con.close(); - } } /** @@ -135,20 +122,12 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, DBTable destinationTable, boolean validateResult) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { if (wrapper.isUsingBulkCopyOptions()) { bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); } @@ -171,18 +150,13 @@ else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { } } bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - bulkCopy.close(); if (validateResult) { validateValues(con, sourceTable, destinationTable); } - } + } catch (SQLException ex) { fail(ex.getMessage()); } - finally { - stmt.dropTable(destinationTable); - con.close(); - } } /** @@ -199,58 +173,54 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable destinationTable, boolean validateResult, boolean fail) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } - } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - if (fail) - fail("bulkCopy.writeToServer did not fail when it should have"); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); - } - } - catch (SQLException ex) { + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + try { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (fail) + fail("bulkCopy.writeToServer did not fail when it should have"); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } + } catch (SQLException ex) { + if (!fail) { + fail(ex.getMessage()); + } + } + finally { + stmt.dropTable(destinationTable); + con.close(); + } + } catch (SQLException e) { if (!fail) { - fail(ex.getMessage()); + fail(e.getMessage()); } - } - finally { - stmt.dropTable(destinationTable); - con.close(); - } + } } /** @@ -269,60 +239,59 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, boolean validateResult, boolean fail, boolean dropDest) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } - } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - if (fail) - fail("bulkCopy.writeToServer did not fail when it should have"); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); - } + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + try { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (fail) + fail("bulkCopy.writeToServer did not fail when it should have"); + bulkCopy.close(); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } + } + catch (SQLException ex) { + if (!fail) { + fail(ex.getMessage()); + } + } + finally { + if (dropDest) { + stmt.dropTable(destinationTable); + } + con.close(); + } } catch (SQLException ex) { if (!fail) { fail(ex.getMessage()); } } - finally { - if (dropDest) { - stmt.dropTable(destinationTable); - } - con.close(); - } } /** @@ -336,24 +305,26 @@ else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { static void validateValues(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { - DBStatement srcStmt = con.createStatement(); - DBStatement dstStmt = con.createStatement(); - DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - - // verify data from sourceType and resultSet - while (srcResultSet.next() && dstResultSet.next()) - for (int i = 1; i <= totalColumns; i++) { - // TODO: check row and column count in both the tables - - Object srcValue, dstValue; - srcValue = srcResultSet.getObject(i); - dstValue = dstResultSet.getObject(i); - - ComparisonUtil.compareExpectedAndActual(destMeta.getColumnType(i), srcValue, dstValue); - } + try (DBStatement srcStmt = con.createStatement(); + DBStatement dstStmt = con.createStatement(); + DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + + // verify data from sourceType and resultSet + while (srcResultSet.next() && dstResultSet.next()) { + for (int i = 1; i <= totalColumns; i++) { + // TODO: check row and column count in both the tables + + Object srcValue, dstValue; + srcValue = srcResultSet.getObject(i); + dstValue = dstResultSet.getObject(i); + + ComparisonUtil.compareExpectedAndActual(destMeta.getColumnType(i), srcValue, dstValue); + } + } + } } /** @@ -365,22 +336,16 @@ static void validateValues(DBConnection con, static void performBulkCopy(BulkCopyTestWrapper bulkWrapper, ISQLServerBulkRecord srcData, DBTable dstTable) { - SQLServerBulkCopy bc; - DBConnection con = new DBConnection(bulkWrapper.getConnectionString()); - DBStatement stmt = con.createStatement(); - try { - bc = new SQLServerBulkCopy(bulkWrapper.getConnectionString()); + try (DBConnection con = new DBConnection(bulkWrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + SQLServerBulkCopy bc = new SQLServerBulkCopy(bulkWrapper.getConnectionString());) { bc.setDestinationTableName(dstTable.getEscapedTableName()); bc.writeToServer(srcData); - bc.close(); validateValues(con, srcData, dstTable); } catch (Exception e) { fail(e.getMessage()); } - finally { - con.close(); - } } /** @@ -395,38 +360,38 @@ static void validateValues( ISQLServerBulkRecord srcData, DBTable destinationTable) throws Exception { - DBStatement dstStmt = con.createStatement(); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - - // reset the counter in ISQLServerBulkRecord, which was incremented during read by BulkCopy - java.lang.reflect.Method method = srcData.getClass().getMethod("reset"); - method.invoke(srcData); - - - // verify data from sourceType and resultSet - while (srcData.next() && dstResultSet.next()) - { - Object[] srcValues = srcData.getRowData(); - for (int i = 1; i <= totalColumns; i++) { - - Object srcValue, dstValue; - srcValue = srcValues[i-1]; - if(srcValue.getClass().getName().equalsIgnoreCase("java.lang.Double")){ - // in case of SQL Server type Float (ie java type double), in float(n) if n is <=24 ie precsion is <=7 SQL Server type Real is returned(ie java type float) - if(destMeta.getPrecision(i) <8) - srcValue = new Float(((Double)srcValue)); - } - dstValue = dstResultSet.getObject(i); - int dstType = destMeta.getColumnType(i); - if(java.sql.Types.TIMESTAMP != dstType - && java.sql.Types.TIME != dstType - && microsoft.sql.Types.DATETIMEOFFSET != dstType){ - // skip validation for temporal types due to rounding eg 7986-10-21 09:51:15.114 is rounded as 7986-10-21 09:51:15.113 in server - ComparisonUtil.compareExpectedAndActual(dstType, srcValue, dstValue); - } - } + try (DBStatement dstStmt = con.createStatement(); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + + // reset the counter in ISQLServerBulkRecord, which was incremented during read by BulkCopy + java.lang.reflect.Method method = srcData.getClass().getMethod("reset"); + method.invoke(srcData); + + // verify data from sourceType and resultSet + while (srcData.next() && dstResultSet.next()) + { + Object[] srcValues = srcData.getRowData(); + for (int i = 1; i <= totalColumns; i++) { + + Object srcValue, dstValue; + srcValue = srcValues[i-1]; + if(srcValue.getClass().getName().equalsIgnoreCase("java.lang.Double")){ + // in case of SQL Server type Float (ie java type double), in float(n) if n is <=24 ie precsion is <=7 SQL Server type Real is returned(ie java type float) + if(destMeta.getPrecision(i) <8) + srcValue = new Float(((Double)srcValue)); + } + dstValue = dstResultSet.getObject(i); + int dstType = destMeta.getColumnType(i); + if(java.sql.Types.TIMESTAMP != dstType + && java.sql.Types.TIME != dstType + && microsoft.sql.Types.DATETIMEOFFSET != dstType){ + // skip validation for temporal types due to rounding eg 7986-10-21 09:51:15.114 is rounded as 7986-10-21 09:51:15.113 in server + ComparisonUtil.compareExpectedAndActual(dstType, srcValue, dstValue); + } + } + } } } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java index a2f5bdaac..3773e75fa 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java @@ -38,13 +38,7 @@ public class BulkCopyTimeoutTest extends BulkCopyTestSetUp { @Test @DisplayName("BulkCopy:test zero timeout") void testZeroTimeOut() throws SQLServerException { - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); - option.setBulkCopyTimeout(0); - bulkWrapper.useBulkCopyOptions(true); - bulkWrapper.setBulkOptions(option); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + testBulkCopyWithTimeout(0); } /** @@ -58,14 +52,18 @@ void testNegativeTimeOut() throws SQLServerException { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override public void execute() throws SQLServerException { - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); - option.setBulkCopyTimeout(-1); - bulkWrapper.useBulkCopyOptions(true); - bulkWrapper.setBulkOptions(option); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + testBulkCopyWithTimeout(-1); } }); } + + private void testBulkCopyWithTimeout(int timeout) throws SQLServerException { + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); + option.setBulkCopyTimeout(timeout); + bulkWrapper.useBulkCopyOptions(true); + bulkWrapper.setBulkOptions(option); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java index 1b45d54a5..bbb83e148 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java @@ -56,13 +56,11 @@ public class ISQLServerBulkRecordIssuesTest extends AbstractTest { @Test public void testVarchar() throws Exception { variation = "testVarchar"; - BulkDat bData = new BulkDat(variation); - String value = "aa"; + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (smallDATA varchar(2))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); bcOperation.close(); @@ -86,19 +84,20 @@ public void testVarchar() throws Exception { @Test public void testSmalldatetime() throws Exception { variation = "testSmalldatetime"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); String value = ("1954-05-22 02:44:00.0").toString(); query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; stmt.executeUpdate(query); - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - bcOperation.close(); - - ResultSet rs = stmt.executeQuery("select * from " + destTable); - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(destTable); + bcOperation.writeToServer(bData); + + try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } + } } } @@ -110,16 +109,14 @@ public void testSmalldatetime() throws Exception { @Test public void testSmalldatetimeOutofRange() throws Exception { variation = "testSmalldatetimeOutofRange"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testSmalldatetimeOutofRange when it it was expected to fail"); } catch (Exception e) { @@ -141,15 +138,13 @@ public void testSmalldatetimeOutofRange() throws Exception { @Test public void testBinaryColumnAsByte() throws Exception { variation = "testBinaryColumnAsByte"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testBinaryColumnAsByte when it it was expected to fail"); } catch (Exception e) { @@ -170,15 +165,13 @@ public void testBinaryColumnAsByte() throws Exception { @Test public void testBinaryColumnAsString() throws Exception { variation = "testBinaryColumnAsString"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testBinaryColumnAsString when it it was expected to fail"); } catch (Exception e) { @@ -199,20 +192,18 @@ public void testBinaryColumnAsString() throws Exception { @Test public void testSendValidValueforBinaryColumnAsString() throws Exception { variation = "testSendValidValueforBinaryColumnAsString"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); - ResultSet rs = stmt.executeQuery("select * from " + destTable); - String value = "0101010000"; - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), "0101010000"); + } } } catch (Exception e) { @@ -258,7 +249,7 @@ public static void afterAllTests() throws SQLException { } -class BulkDat implements ISQLServerBulkRecord { +class BulkData implements ISQLServerBulkRecord { boolean isStringData = false; private class ColumnMetadata { @@ -286,7 +277,7 @@ private class ColumnMetadata { int counter = 0; int rowCount = 1; - BulkDat(String variation) { + BulkData(String variation) { if (variation.equalsIgnoreCase("testVarchar")) { isStringData = true; columnMetadata = new HashMap<>(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java index 8898be8b9..90ba5d0ac 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java @@ -33,10 +33,6 @@ @DisplayName("BVT Test") public class bvtTest extends bvtTestSetup { private static String driverNamePattern = "Microsoft JDBC Driver \\d.\\d for SQL Server"; - private static DBResultSet rs = null; - private static DBPreparedStatement pstmt = null; - private static DBConnection conn = null; - private static DBStatement stmt = null; /** * Connect to specified server and close the connection @@ -46,13 +42,7 @@ public class bvtTest extends bvtTestSetup { @Test @DisplayName("test connection") public void testConnection() throws SQLException { - try { - conn = new DBConnection(connectionString); - conn.close(); - } - finally { - terminateVariation(); - } + try (DBConnection conn = new DBConnection(connectionString)) {} } /** @@ -62,15 +52,11 @@ public void testConnection() throws SQLException { */ @Test public void testConnectionIsClosed() throws SQLException { - try { - conn = new DBConnection(connectionString); + try (DBConnection conn = new DBConnection(connectionString)) { assertTrue(!conn.isClosed(), "BVT connection should not be closed"); conn.close(); assertTrue(conn.isClosed(), "BVT connection should not be open"); } - finally { - terminateVariation(); - } } /** @@ -80,8 +66,7 @@ public void testConnectionIsClosed() throws SQLException { */ @Test public void testDriverNameAndDriverVersion() throws SQLException { - try { - conn = new DBConnection(connectionString); + try (DBConnection conn = new DBConnection(connectionString)) { DatabaseMetaData metaData = conn.getMetaData(); Pattern p = Pattern.compile(driverNamePattern); Matcher m = p.matcher(metaData.getDriverName()); @@ -90,9 +75,6 @@ public void testDriverNameAndDriverVersion() throws SQLException { if (parts.length != 4) assertTrue(true, "Driver version number should be four parts! "); } - finally { - terminateVariation(); - } } /** @@ -103,16 +85,12 @@ public void testDriverNameAndDriverVersion() throws SQLException { @Test public void testCreateStatement() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - String query = "SELECT * FROM " + table1.getEscapedTableName() + ";"; - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName() + ";"; + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { rs.verify(table1); - rs.close(); - } - finally { - terminateVariation(); } } @@ -124,14 +102,10 @@ public void testCreateStatement() throws SQLException { @Test public void testCreateStatementWithQueryTimeout() throws SQLException { - try { - conn = new DBConnection(connectionString + ";querytimeout=10"); - stmt = conn.createStatement(); + try (DBConnection conn = new DBConnection(connectionString + ";querytimeout=10"); + DBStatement stmt = conn.createStatement()) { assertEquals(10, stmt.getQueryTimeout()); } - finally { - terminateVariation(); - } } /** @@ -144,11 +118,11 @@ public void testCreateStatementWithQueryTimeout() throws SQLException { @Test public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY); - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); rs.verifyCurrentRow(table1); @@ -164,9 +138,6 @@ public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundExce } rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -178,11 +149,9 @@ public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundExce */ @Test public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFoundException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY); - - rs = stmt.selectAll(table1); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY); + DBResultSet rs = stmt.selectAll(table1)) { rs.next(); rs.verifyCurrentRow(table1); rs.afterLast(); @@ -190,9 +159,6 @@ public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFou rs.verifyCurrentRow(table1); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -204,12 +170,11 @@ public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFou @Test public void testStmtScrollSensitiveReadOnly() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); rs.next(); rs.verifyCurrentRow(table1); @@ -219,9 +184,6 @@ public void testStmtScrollSensitiveReadOnly() throws SQLException { rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -232,13 +194,12 @@ public void testStmtScrollSensitiveReadOnly() throws SQLException { */ @Test public void testStmtForwardOnlyUpdateable() throws SQLException { + + String query = "SELECT * FROM " + table1.getEscapedTableName(); - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_UPDATABLE); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_UPDATABLE); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); // Verify resultset behavior @@ -255,9 +216,6 @@ public void testStmtForwardOnlyUpdateable() throws SQLException { } rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -269,12 +227,11 @@ public void testStmtForwardOnlyUpdateable() throws SQLException { @Test public void testStmtScrollSensitiveUpdatable() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE); + DBResultSet rs = stmt.executeQuery(query)) { // Verify resultset behavior rs.next(); @@ -285,9 +242,6 @@ public void testStmtScrollSensitiveUpdatable() throws SQLException { rs.absolute(1); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -298,11 +252,9 @@ public void testStmtScrollSensitiveUpdatable() throws SQLException { @Test public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_DYNAMIC_CONCUR_OPTIMISTIC); - - rs = stmt.selectAll(table1); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_DYNAMIC_CONCUR_OPTIMISTIC); + DBResultSet rs = stmt.selectAll(table1)) { // Verify resultset behavior rs.next(); @@ -310,9 +262,6 @@ public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { rs.previous(); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -323,23 +272,16 @@ public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { @Test public void testStmtSserverCursorForwardOnly() throws SQLException { - try { - conn = new DBConnection(connectionString); - DBResultSetTypes rsType = DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY; - stmt = conn.createStatement(rsType.resultsetCursor, rsType.resultSetConcurrency); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - - rs = stmt.executeQuery(query); - + DBResultSetTypes rsType = DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY; + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(rsType.resultsetCursor, rsType.resultSetConcurrency); + DBResultSet rs = stmt.executeQuery(query)) { // Verify resultset behavior rs.next(); rs.verify(table1); } - finally { - terminateVariation(); - } - } /** @@ -350,21 +292,17 @@ public void testStmtSserverCursorForwardOnly() throws SQLException { @Test public void testCreatepreparedStatement() throws SQLException { - try { - conn = new DBConnection(connectionString); - String colName = table1.getColumnName(7); - String value = table1.getRowData(7, 0).toString(); + String colName = table1.getColumnName(7); + String value = table1.getRowData(7, 0).toString(); + String query = "SELECT * from " + table1.getEscapedTableName() + " where [" + colName + "] = ? "; + + try (DBConnection conn = new DBConnection(connectionString); + DBPreparedStatement pstmt = conn.prepareStatement(query)) { - String query = "SELECT * from " + table1.getEscapedTableName() + " where [" + colName + "] = ? "; - - pstmt = conn.prepareStatement(query); pstmt.setObject(1, new BigDecimal(value)); - - rs = pstmt.executeQuery(); + DBResultSet rs = pstmt.executeQuery(); rs.verify(table1); - } - finally { - terminateVariation(); + rs.close(); } } @@ -376,19 +314,14 @@ public void testCreatepreparedStatement() throws SQLException { @Test public void testResultSet() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); - + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { // verify resultSet rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -399,12 +332,11 @@ public void testResultSet() throws SQLException { @Test public void testResultSetAndClose() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { try { if (null != rs) @@ -414,9 +346,6 @@ public void testResultSetAndClose() throws SQLException { fail(e.toString()); } } - finally { - terminateVariation(); - } } /** @@ -426,21 +355,15 @@ public void testResultSetAndClose() throws SQLException { */ @Test public void testTwoResultsetsDifferentStmt() throws SQLException { + + String query = "SELECT * FROM " + table1.getEscapedTableName(); + String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - DBStatement stmt1 = null; - DBStatement stmt2 = null; - DBResultSet rs1 = null; - DBResultSet rs2 = null; - try { - conn = new DBConnection(connectionString); - stmt1 = conn.createStatement(); - stmt2 = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs1 = stmt1.executeQuery(query); - - String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - rs2 = stmt2.executeQuery(query2); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt1 = conn.createStatement(); + DBStatement stmt2 = conn.createStatement(); + DBResultSet rs1 = stmt1.executeQuery(query); + DBResultSet rs2 = stmt2.executeQuery(query2)) { // Interleave resultset calls rs1.next(); @@ -450,25 +373,9 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { rs1.next(); rs1.verifyCurrentRow(table1); rs1.verify(table1); - rs1.close(); rs2.next(); rs2.verify(table2); } - finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - if (null != stmt1) { - stmt1.close(); - } - if (null != stmt2) { - stmt2.close(); - } - terminateVariation(); - } } /** @@ -479,17 +386,13 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { @Test public void testTwoResultsetsSameStmt() throws SQLException { - DBResultSet rs1 = null; - DBResultSet rs2 = null; - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs1 = stmt.executeQuery(query); - - String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - rs2 = stmt.executeQuery(query2); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + String query2 = "SELECT * FROM " + table2.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs1 = stmt.executeQuery(query); + DBResultSet rs2 = stmt.executeQuery(query2)) { // Interleave resultset calls. rs is expected to be closed try { @@ -506,19 +409,9 @@ public void testTwoResultsetsSameStmt() throws SQLException { catch (SQLException e) { assertEquals(e.toString(), "com.microsoft.sqlserver.jdbc.SQLServerException: The result set is closed."); } - rs1.close(); rs2.next(); rs2.verify(table2); } - finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - terminateVariation(); - } } /** @@ -528,12 +421,10 @@ public void testTwoResultsetsSameStmt() throws SQLException { */ @Test public void testResultSetAndCloseStmt() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { stmt.close(); // this should close the resultSet try { @@ -542,10 +433,7 @@ public void testResultSetAndCloseStmt() throws SQLException { catch (SQLException e) { assertEquals(e.toString(), "com.microsoft.sqlserver.jdbc.SQLServerException: The result set is closed."); } - assertTrue(true, "Previouse one should have thrown exception!"); - } - finally { - terminateVariation(); + assertTrue(true, "Previous one should have thrown exception!"); } } @@ -557,18 +445,12 @@ public void testResultSetAndCloseStmt() throws SQLException { @Test public void testResultSetSelectMethod() throws SQLException { - try { - conn = new DBConnection(connectionString + ";selectMethod=cursor;"); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); - + String query = "SELECT * FROM " + table1.getEscapedTableName(); + try (DBConnection conn = new DBConnection(connectionString + ";selectMethod=cursor;"); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -579,34 +461,10 @@ public void testResultSetSelectMethod() throws SQLException { @AfterAll public static void terminate() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { stmt.execute("if object_id('" + table1.getEscapedTableName() + "','U') is not null" + " drop table " + table1.getEscapedTableName()); stmt.execute("if object_id('" + table2.getEscapedTableName() + "','U') is not null" + " drop table " + table2.getEscapedTableName()); } - finally { - terminateVariation(); - } - } - - /** - * cleanup after tests - * - * @throws SQLException - */ - public static void terminateVariation() throws SQLException { - if (conn != null && !conn.isClosed()) { - try { - conn.close(); - } - finally { - if (null != rs) - rs.close(); - if (null != stmt) - stmt.close(); - } - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java index 684bfd81d..0306d6f1d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java @@ -24,18 +24,14 @@ */ @RunWith(JUnitPlatform.class) public class bvtTestSetup extends AbstractTest { - private static DBConnection conn = null; - private static DBStatement stmt = null; static DBTable table1; static DBTable table2; @BeforeAll public static void init() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { // create tables table1 = new DBTable(true); stmt.createTable(table1); @@ -44,14 +40,5 @@ public static void init() throws SQLException { stmt.createTable(table2); stmt.populateTable(table2); } - finally { - if (null != stmt) { - stmt.close(); - } - if (null != conn && !conn.isClosed()) { - conn.close(); - } - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java index d0271714d..84a7f9026 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -46,9 +46,9 @@ public static void setupTest() throws SQLException { Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); Utils.dropProcedureIfExists(setNullProcedureName, stmt); - createGUIDTable(); - createGUIDStoredProcedure(); - createSetNullPreocedure(); + createGUIDTable(stmt); + createGUIDStoredProcedure(stmt); + createSetNullPreocedure(stmt); } /** @@ -59,17 +59,14 @@ public static void setupTest() throws SQLException { @Test public void getStringGUIDTest() throws SQLException { - SQLServerCallableStatement callableStatement = null; - try { - String sql = "{call " + outputProcedureNameGUID + "(?)}"; - - callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql); + String sql = "{call " + outputProcedureNameGUID + "(?)}"; + + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql)) { UUID originalValue = UUID.randomUUID(); callableStatement.registerOutParameter(1, microsoft.sql.Types.GUID); callableStatement.setObject(1, originalValue.toString(), microsoft.sql.Types.GUID); - callableStatement.execute(); String retrievedValue = callableStatement.getString(1); @@ -77,11 +74,6 @@ public void getStringGUIDTest() throws SQLException { assertEquals(originalValue.toString().toLowerCase(), retrievedValue.toLowerCase()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } /** @@ -93,17 +85,14 @@ public void getStringGUIDTest() throws SQLException { public void getSetNullWithTypeVarchar() throws SQLException { String polishchar = "\u0143"; - SQLServerCallableStatement cs = null; - SQLServerCallableStatement cs2 = null; - try { - SQLServerDataSource ds = new SQLServerDataSource(); - ds.setURL(connectionString); - ds.setSendStringParametersAsUnicode(true); - connection = ds.getConnection(); + SQLServerDataSource ds = new SQLServerDataSource(); + ds.setURL(connectionString); + ds.setSendStringParametersAsUnicode(true); + String sql = "{? = call " + setNullProcedureName + " (?,?)}"; + try (Connection connection = ds.getConnection(); + SQLServerCallableStatement cs = (SQLServerCallableStatement) connection.prepareCall(sql); + SQLServerCallableStatement cs2 = (SQLServerCallableStatement) connection.prepareCall(sql)){ - String sql = "{? = call " + setNullProcedureName + " (?,?)}"; - - cs = (SQLServerCallableStatement) connection.prepareCall(sql); cs.registerOutParameter(1, Types.INTEGER); cs.setString(2, polishchar); cs.setString(3, null); @@ -112,7 +101,6 @@ public void getSetNullWithTypeVarchar() throws SQLException { String expected = cs.getString(3); - cs2 = (SQLServerCallableStatement) connection.prepareCall(sql); cs2.registerOutParameter(1, Types.INTEGER); cs2.setString(2, polishchar); cs2.setNull(3, Types.VARCHAR); @@ -120,17 +108,9 @@ public void getSetNullWithTypeVarchar() throws SQLException { cs2.execute(); String actual = cs2.getString(3); - + assertEquals(expected, actual); } - finally { - if (null != cs) { - cs.close(); - } - if (null != cs2) { - cs2.close(); - } - } } /** @@ -152,17 +132,17 @@ public static void cleanup() throws SQLException { } } - private static void createGUIDStoredProcedure() throws SQLException { + private static void createGUIDStoredProcedure(Statement stmt) throws SQLException { String sql = "CREATE PROCEDURE " + outputProcedureNameGUID + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " + tableNameGUID + ";"; stmt.execute(sql); } - private static void createGUIDTable() throws SQLException { + private static void createGUIDTable(Statement stmt) throws SQLException { String sql = "CREATE TABLE " + tableNameGUID + " (c1 uniqueidentifier null)"; stmt.execute(sql); } - private static void createSetNullPreocedure() throws SQLException { + private static void createSetNullPreocedure(Statement stmt) throws SQLException { stmt.execute("create procedure " + setNullProcedureName + " (@p1 nvarchar(255), @p2 nvarchar(255) output) as select @p2=@p1 return 0"); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java index c8a415540..2acf5f002 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -123,8 +123,7 @@ public void testEncryptedConnection() throws SQLException { ds.setEncrypt(true); ds.setTrustServerCertificate(true); ds.setPacketSize(8192); - Connection con = ds.getConnection(); - con.close(); + try(Connection con = ds.getConnection()) {} } @Test @@ -172,25 +171,25 @@ public void testConnectionEvents() throws SQLException { // Attach the Event listener and listen for connection events. MyEventListener myE = new MyEventListener(); - pooledConnection.addConnectionEventListener(myE); // ConnectionListener - // implements - // ConnectionEventListener - Connection con = pooledConnection.getConnection(); - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - - boolean exceptionThrown = false; - try { - // raise a severe exception and make sure that the connection is not - // closed. - stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + pooledConnection.addConnectionEventListener(myE); // ConnectionListener implements ConnectionEventListener + + try(Connection con = pooledConnection.getConnection(); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + + boolean exceptionThrown = false; + try { + // raise a severe exception and make sure that the connection is not + // closed. + stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + } + catch (Exception e) { + exceptionThrown = true; + } + assertTrue(exceptionThrown, "Expected exception is not thrown."); + + // Check to see if error occurred. + assertTrue(myE.errorOccurred, "Error occurred is not called."); } - catch (Exception e) { - exceptionThrown = true; - } - assertTrue(exceptionThrown, "Expected exception is not thrown."); - - // Check to see if error occurred. - assertTrue(myE.errorOccurred, "Error occurred is not called."); // make sure that connection is closed. } @@ -204,23 +203,18 @@ public void testConnectionPoolGetTwice() throws SQLException { // Attach the Event listener and listen for connection events. MyEventListener myE = new MyEventListener(); - pooledConnection.addConnectionEventListener(myE); // ConnectionListener - // implements - // ConnectionEventListener - - Connection con = pooledConnection.getConnection(); - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + pooledConnection.addConnectionEventListener(myE); // ConnectionListener implements ConnectionEventListener - // raise a non severe exception and make sure that the connection is not - // closed. + Connection con = pooledConnection.getConnection(); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + // raise a non severe exception and make sure that the connection is not closed. stmt.executeUpdate("RAISERROR ('foo', 3,1) WITH LOG"); - // not a serious error there should not be any errors. assertTrue(!myE.errorOccurred, "Error occurred is called."); // check to make sure that connection is not closed. - assertTrue(!con.isClosed(), "Connection is closed."); - - con.close(); + assertTrue(!con.isClosed(), "Connection is closed."); + stmt.close(); + con.close(); // check to make sure that connection is closed. assertTrue(con.isClosed(), "Connection is not closed."); } @@ -242,36 +236,34 @@ public void testConnectionClosed() throws SQLException { exceptionThrown = true; } assertTrue(exceptionThrown, "Expected exception is not thrown."); - + // check to make sure that connection is closed. assertTrue(con.isClosed(), "Connection is not closed."); } @Test public void testIsWrapperFor() throws SQLException, ClassNotFoundException { - Connection conn = DriverManager.getConnection(connectionString); - SQLServerConnection ssconn = (SQLServerConnection) conn; - boolean isWrapper; - isWrapper = ssconn.isWrapperFor(ssconn.getClass()); - assertTrue(isWrapper, "SQLServerConnection supports unwrapping"); - assertEquals(ssconn.TRANSACTION_SNAPSHOT, ssconn.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); - - isWrapper = ssconn.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); - assertTrue(isWrapper, "ISQLServerConnection supports unwrapping"); - ISQLServerConnection iSql = (ISQLServerConnection) ssconn.unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); - assertEquals(iSql.TRANSACTION_SNAPSHOT, iSql.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); - - ssconn.unwrap(Class.forName("java.sql.Connection")); - - conn.close(); + try(Connection conn = DriverManager.getConnection(connectionString); + SQLServerConnection ssconn = (SQLServerConnection) conn) { + boolean isWrapper; + isWrapper = ssconn.isWrapperFor(ssconn.getClass()); + assertTrue(isWrapper, "SQLServerConnection supports unwrapping"); + assertEquals(ssconn.TRANSACTION_SNAPSHOT, ssconn.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); + + isWrapper = ssconn.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + assertTrue(isWrapper, "ISQLServerConnection supports unwrapping"); + ISQLServerConnection iSql = (ISQLServerConnection) ssconn.unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + assertEquals(iSql.TRANSACTION_SNAPSHOT, iSql.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); + + ssconn.unwrap(Class.forName("java.sql.Connection")); + } } @Test public void testNewConnection() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - assertTrue(conn.isValid(0), "Newly created connection should be valid"); - - conn.close(); + try(SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + assertTrue(conn.isValid(0), "Newly created connection should be valid"); + } } @Test @@ -283,46 +275,46 @@ public void testClosedConnection() throws SQLException { @Test public void testNegativeTimeout() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - try { - conn.isValid(-42); - throw new Exception("No exception thrown with negative timeout"); - } - catch (SQLException e) { - assertEquals(e.getMessage(), "The query timeout value -42 is not valid.", "Wrong exception message"); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try { + conn.isValid(-42); + throw new Exception("No exception thrown with negative timeout"); + } + catch (SQLException e) { + assertEquals(e.getMessage(), "The query timeout value -42 is not valid.", "Wrong exception message"); + } } - - conn.close(); } @Test public void testDeadConnection() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), "Skipping test case on Azure SQL."); - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";responseBuffering=adaptive"); - Statement stmt = null; - - String tableName = RandomUtil.getIdentifier("Table"); - tableName = DBTable.escapeIdentifier(tableName); - - conn.setAutoCommit(false); - stmt = conn.createStatement(); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); - for (int i = 0; i < 80; i++) { - stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); - } - conn.commit(); - try { - stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " + tableName - + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); - } - catch (SQLServerException e) { - assertEquals(e.getMessage(), "Connection reset", "Unknown Exception"); - } - finally { - DriverManager.getConnection(connectionString).createStatement().execute("drop table " + tableName); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";responseBuffering=adaptive")) { + + Statement stmt = null; + String tableName = RandomUtil.getIdentifier("Table"); + tableName = DBTable.escapeIdentifier(tableName); + + conn.setAutoCommit(false); + stmt = conn.createStatement(); + stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); + for (int i = 0; i < 80; i++) { + stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); + } + conn.commit(); + try { + stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " + tableName + + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); + } + catch (SQLServerException e) { + assertEquals(e.getMessage(), "Connection reset", "Unknown Exception"); + } + finally { + DriverManager.getConnection(connectionString).createStatement().execute("drop table " + tableName); + } + assertEquals(conn.isValid(5), false, "Dead connection should be invalid"); } - assertEquals(conn.isValid(5), false, "Dead connection should be invalid"); } @Test diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java index 9645d5b95..f71da3f7f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java @@ -11,13 +11,13 @@ import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; -import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBTable; import com.microsoft.sqlserver.testframework.util.RandomUtil; @@ -32,26 +32,27 @@ public void testDatabaseMetaData() throws SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); - Connection con = ds.getConnection(); - - // drop function String sqlDropFunction = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo]." + functionName + "')" + "and xtype in (N'FN', N'IF', N'TF'))" + "drop function " + functionName; - con.createStatement().execute(sqlDropFunction); - - // create function String sqlCreateFunction = "CREATE FUNCTION " + functionName + " (@text varchar(8000), @delimiter varchar(20) = ' ') RETURNS @Strings TABLE " + "(position int IDENTITY PRIMARY KEY, value varchar(8000)) AS BEGIN INSERT INTO @Strings VALUES ('DDD') RETURN END "; - con.createStatement().execute(sqlCreateFunction); - - DatabaseMetaData md = con.getMetaData(); - ResultSet arguments = md.getProcedureColumns(null, null, null, "@TABLE_RETURN_VALUE"); - - if (arguments.next()) { - arguments.getString("COLUMN_NAME"); - arguments.getString("DATA_TYPE"); // call this function to make sure it does not crash + + try (Connection con = ds.getConnection(); + Statement stmt = con.createStatement()) { + // drop function + stmt.execute(sqlDropFunction); + // create function + stmt.execute(sqlCreateFunction); + + DatabaseMetaData md = con.getMetaData(); + try (ResultSet arguments = md.getProcedureColumns(null, null, null, "@TABLE_RETURN_VALUE")) { + + if (arguments.next()) { + arguments.getString("COLUMN_NAME"); + arguments.getString("DATA_TYPE"); // call this function to make sure it does not crash + } + } + stmt.execute(sqlDropFunction); } - - con.createStatement().execute(sqlDropFunction); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java index 08ba2a58a..57803a32e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java @@ -43,36 +43,34 @@ public void testNativeMSSQLDataSource() throws SQLException { @Test public void testSerialization() throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - ObjectOutput objectOutput = new ObjectOutputStream(outputStream); - - SQLServerDataSource ds = new SQLServerDataSource(); - ds.setLogWriter(new PrintWriter(new ByteArrayOutputStream())); - - objectOutput.writeObject(ds); - objectOutput.flush(); + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ObjectOutput objectOutput = new ObjectOutputStream(outputStream)) { + SQLServerDataSource ds = new SQLServerDataSource(); + ds.setLogWriter(new PrintWriter(new ByteArrayOutputStream())); + + objectOutput.writeObject(ds); + objectOutput.flush(); + } } @Test - public void testDSNormal() throws SQLServerException, ClassNotFoundException, IOException { + public void testDSNormal() throws ClassNotFoundException, IOException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); - Connection conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} ds = testSerial(ds); - conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} } @Test - public void testDSTSPassword() throws SQLServerException, ClassNotFoundException, IOException { + public void testDSTSPassword() throws ClassNotFoundException, IOException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); System.setProperty("java.net.preferIPv6Addresses", "true"); ds.setURL(connectionString); ds.setTrustStorePassword("wrong_password"); - Connection conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} ds = testSerial(ds); - try { - conn = ds.getConnection(); - } + try (Connection conn = ds.getConnection()) {} catch (SQLServerException e) { assertEquals("The DataSource trustStore password needs to be set.", e.getMessage()); } @@ -106,13 +104,16 @@ public void testInterfaceWrapping() throws ClassNotFoundException, SQLException } private SQLServerDataSource testSerial(SQLServerDataSource ds) throws IOException, ClassNotFoundException { - java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); - java.io.ObjectOutput objectOutput = new java.io.ObjectOutputStream(outputStream); - objectOutput.writeObject(ds); - objectOutput.flush(); - ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray())); - SQLServerDataSource dtn; - dtn = (SQLServerDataSource) in.readObject(); - return dtn; + try (java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); + java.io.ObjectOutput objectOutput = new java.io.ObjectOutputStream(outputStream)) { + objectOutput.writeObject(ds); + objectOutput.flush(); + + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray()))) { + SQLServerDataSource dtn; + dtn = (SQLServerDataSource) in.readObject(); + return dtn; + } + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java index 1c254b54b..1a51deb34 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -59,17 +59,15 @@ public void testPooling() throws SQLException { XADataSource1.setDatabaseName("tempdb"); PooledConnection pc = XADataSource1.getPooledConnection(); - Connection conn = pc.getConnection(); - - // create table in tempdb database - conn.createStatement().execute("create table [" + tempTableName + "] (myid int)"); - conn.createStatement().execute("insert into [" + tempTableName + "] values (1)"); - conn.close(); - - conn = pc.getConnection(); + try (Connection conn = pc.getConnection()) { + + // create table in tempdb database + conn.createStatement().execute("create table [" + tempTableName + "] (myid int)"); + conn.createStatement().execute("insert into [" + tempTableName + "] values (1)"); + } boolean tempTableFileRemoved = false; - try { + try (Connection conn = pc.getConnection()) { conn.createStatement().executeQuery("select * from [" + tempTableName + "]"); } catch (SQLServerException e) { @@ -109,12 +107,12 @@ public void testConnectionPoolConnFunctions() throws SQLException { ds.setURL(connectionString); PooledConnection pc = ds.getPooledConnection(); - Connection con = pc.getConnection(); - - Statement statement = con.createStatement(); - statement.execute(sql1); - statement.execute(sql2); - con.clearWarnings(); + try (Connection con = pc.getConnection(); + Statement statement = con.createStatement()) { + statement.execute(sql1); + statement.execute(sql2); + con.clearWarnings(); + } pc.close(); } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java index 51e0c7aa2..a6ae11d07 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java @@ -21,7 +21,7 @@ /* * Wrapper class for SQLServerConnection */ -public class DBConnection extends AbstractParentWrapper { +public class DBConnection extends AbstractParentWrapper implements AutoCloseable { private double serverversion = 0; // TODO: add Isolation Level diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java index 0851f3907..d281effca 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java @@ -36,7 +36,7 @@ * */ -public class DBResultSet extends AbstractParentWrapper { +public class DBResultSet extends AbstractParentWrapper implements AutoCloseable { // TODO: add cursors // TODO: add resultSet level holdability diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java index 8d4787120..00b006026 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java @@ -21,7 +21,7 @@ * @author Microsoft * */ -public class DBStatement extends AbstractParentWrapper { +public class DBStatement extends AbstractParentWrapper implements AutoCloseable{ // TODO: support PreparedStatement and CallableStatement // TODO: add stmt level holdability @@ -120,7 +120,7 @@ public void close() throws SQLException { if ((null != dbresultSet) && null != ((ResultSet) dbresultSet.product())) { ((ResultSet) dbresultSet.product()).close(); } - statement.close(); + //statement.close(); } /** From 55641c873827382881ea7372848bb558721c02a5 Mon Sep 17 00:00:00 2001 From: Afsaneh Rafighi Date: Thu, 5 Oct 2017 09:34:44 -0700 Subject: [PATCH 37/68] avoid creating connection for termination --- .../jdbc/unit/statement/CallableMixedTest.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java index 2fff7da55..e93f1c150 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java @@ -84,8 +84,8 @@ public void datatypesTest() throws SQLException { rs = callableStatement.executeQuery(); rs.close(); } + terminateVariation(statement); } - terminateVariation(); } /** @@ -93,10 +93,8 @@ public void datatypesTest() throws SQLException { * * @throws SQLException */ - private void terminateVariation() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement()) { - Utils.dropTableIfExists(tableName, statement); - Utils.dropProcedureIfExists(procName, statement); - } + private void terminateVariation(Statement statement) throws SQLException { + Utils.dropTableIfExists(tableName, statement); + Utils.dropProcedureIfExists(procName, statement); } } From 8c0ebf26e8b424eb33ccbe49d3a238d5ca6c43b7 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Thu, 5 Oct 2017 10:32:15 -0700 Subject: [PATCH 38/68] remove null check and change Set object name --- .../sqlserver/jdbc/SQLServerDataTable.java | 16 +++++++--------- .../com/microsoft/sqlserver/jdbc/TVP.java | 19 +++++++++---------- 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index 939ac5163..34fbd2314 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -26,7 +26,7 @@ public final class SQLServerDataTable { int rowCount = 0; int columnCount = 0; Map columnMetadata = null; - Set columnList = null; + Set columnNames = null; Map rows = null; private String tvpName = null; @@ -40,7 +40,7 @@ public final class SQLServerDataTable { // Name used in CREATE TYPE public SQLServerDataTable() throws SQLServerException { columnMetadata = new LinkedHashMap<>(); - columnList = new HashSet<>(); + columnNames = new HashSet<>(); rows = new HashMap<>(); } @@ -106,13 +106,11 @@ public synchronized void addColumnMetadata(SQLServerDataColumn column) throws SQ * when a duplicate column exists */ private void checkDuplicateColumnName(String columnName) throws SQLServerException { - if (null != columnList) { - //columnList.add will return false if the same column name already exists - if (!columnList.add(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } + //columnList.add will return false if the same column name already exists + if (!columnNames.add(columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java index 21f2c061d..a99ee8a37 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java @@ -50,7 +50,7 @@ class TVP { Iterator> sourceDataTableRowIterator = null; ISQLServerDataRecord sourceRecord = null; TVPType tvpType = null; - Set columnList = null; + Set columnNames = null; // MultiPartIdentifierState enum MPIState { @@ -97,7 +97,7 @@ void initTVP(TVPType type, ISQLServerDataRecord tvpRecord) throws SQLServerException { initTVP(TVPType.ISQLServerDataRecord, tvpPartName); sourceRecord = tvpRecord; - columnList = new HashSet<>(); + columnNames = new HashSet<>(); // Populate TVP metdata from ISQLServerDataRecord. populateMetadataFromDataRecord(); @@ -189,15 +189,14 @@ void populateMetadataFromDataRecord() throws SQLServerException { throw new SQLServerException(SQLServerException.getErrString("R_TVPEmptyMetadata"), null); } for (int i = 0; i < sourceRecord.getColumnCount(); i++) { - // Make a copy here as we do not want to change user's metadata. - if (null != columnList) { - //columnList.add will return false if the same column name already exists - if (!columnList.add(sourceRecord.getColumnMetaData(i + 1).columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {sourceRecord.getColumnMetaData(i + 1).columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } + //columnList.add will return false if the same column name already exists + if (!columnNames.add(sourceRecord.getColumnMetaData(i + 1).columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {sourceRecord.getColumnMetaData(i + 1).columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); } + + // Make a copy here as we do not want to change user's metadata. SQLServerMetaData metaData = new SQLServerMetaData(sourceRecord.getColumnMetaData(i + 1)); columnMetadata.put(i, metaData); } From e2ec02e6519827d18117726090a56dbf300a1af0 Mon Sep 17 00:00:00 2001 From: Gord Thompson Date: Fri, 6 Oct 2017 15:27:37 -0600 Subject: [PATCH 39/68] tweak to preserve original parameter name for exception message --- .../sqlserver/jdbc/SQLServerCallableStatement.java | 9 ++++++--- .../jdbc/callablestatement/CallableStatementTest.java | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java index 15777f4ca..5ad8689c8 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java @@ -1453,8 +1453,11 @@ public NClob getNClob(String parameterName) throws SQLException { // handle `@name` as well as `name`, since `@name` is what's returned // by DatabaseMetaData#getProcedureColumns + String columnNameWithoutAtSign = null; if (columnName.startsWith("@")) { - columnName = columnName.substring(1, columnName.length()); + columnNameWithoutAtSign = columnName.substring(1, columnName.length()); + } else { + columnNameWithoutAtSign = columnName; } // In order to be as accurate as possible when locating parameter name @@ -1471,7 +1474,7 @@ public NClob getNClob(String parameterName) throws SQLException { for (i = 0; i < l; i++) { String sParam = paramNames.get(i); sParam = sParam.substring(1, sParam.length()); - if (sParam.equals(columnName)) { + if (sParam.equals(columnNameWithoutAtSign)) { matchPos = i; break; } @@ -1483,7 +1486,7 @@ public NClob getNClob(String parameterName) throws SQLException { for (i = 0; i < l; i++) { String sParam = paramNames.get(i); sParam = sParam.substring(1, sParam.length()); - if (sParam.equalsIgnoreCase(columnName)) { + if (sParam.equalsIgnoreCase(columnNameWithoutAtSign)) { matchPos = i; break; } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java index 9c682e849..ce738ff2e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -173,7 +173,9 @@ public void inputParamsTest() throws SQLException { cs3.setString("@whatever", "junk"); fail("SQLServerException should have been thrown"); } catch (SQLServerException sse) { - // expected + if (!sse.getMessage().startsWith("Parameter @whatever was not defined")) { + fail("Unexpected content in exception message"); + } } } From d4eadd6ef1cacb10f97f58d1f549bf275ac7b76a Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 6 Oct 2017 14:47:58 -0700 Subject: [PATCH 40/68] Check for "Account Locked" SQL Exception 18486 while connecitng to SQL Server 2008/2012 and throw Exception --- .../java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java | 1 + .../java/com/microsoft/sqlserver/jdbc/SQLServerException.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 730f13bf7..35578f24b 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -1991,6 +1991,7 @@ else if (null == currentPrimaryPlaceHolder) { catch (SQLServerException sqlex) { if ((SQLServerException.LOGON_FAILED == sqlex.getErrorCode()) // actual logon failed, i.e. bad password || (SQLServerException.PASSWORD_EXPIRED == sqlex.getErrorCode()) // actual logon failed, i.e. password isExpired + || (SQLServerException.USER_ACCOUNT_LOCKED == sqlex.getErrorCode()) // actual logon failed, i.e. password isExpired || (SQLServerException.DRIVER_ERROR_INVALID_TDS == sqlex.getDriverErrorCode()) // invalid TDS received from server || (SQLServerException.DRIVER_ERROR_SSL_FAILED == sqlex.getDriverErrorCode()) // failure negotiating SSL || (SQLServerException.DRIVER_ERROR_INTERMITTENT_TLS_FAILED == sqlex.getDriverErrorCode()) // failure TLS1.2 diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java index e8ed55d5a..20e18255b 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java @@ -59,6 +59,7 @@ public final class SQLServerException extends java.sql.SQLException { // SQL error values (from sqlerrorcodes.h) static final int LOGON_FAILED = 18456; static final int PASSWORD_EXPIRED = 18488; + static final int USER_ACCOUNT_LOCKED = 18486; static java.util.logging.Logger exLogger = java.util.logging.Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SQLServerException"); // Facility for driver-specific error codes From 4a1409a848b8e578de51d9de8f7d9c5c8edc9839 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 6 Oct 2017 15:30:34 -0700 Subject: [PATCH 41/68] Updated comment for Locked User Account in SQLServerConnection.java --- .../java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 35578f24b..be9056c60 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -1991,7 +1991,7 @@ else if (null == currentPrimaryPlaceHolder) { catch (SQLServerException sqlex) { if ((SQLServerException.LOGON_FAILED == sqlex.getErrorCode()) // actual logon failed, i.e. bad password || (SQLServerException.PASSWORD_EXPIRED == sqlex.getErrorCode()) // actual logon failed, i.e. password isExpired - || (SQLServerException.USER_ACCOUNT_LOCKED == sqlex.getErrorCode()) // actual logon failed, i.e. password isExpired + || (SQLServerException.USER_ACCOUNT_LOCKED == sqlex.getErrorCode()) // actual logon failed, i.e. user account locked || (SQLServerException.DRIVER_ERROR_INVALID_TDS == sqlex.getDriverErrorCode()) // invalid TDS received from server || (SQLServerException.DRIVER_ERROR_SSL_FAILED == sqlex.getDriverErrorCode()) // failure negotiating SSL || (SQLServerException.DRIVER_ERROR_INTERMITTENT_TLS_FAILED == sqlex.getDriverErrorCode()) // failure TLS1.2 From adf10ea484bdc9a2d39feb6a119650446a3f17c2 Mon Sep 17 00:00:00 2001 From: Peter Bae Date: Fri, 6 Oct 2017 15:58:09 -0700 Subject: [PATCH 42/68] Refactoring the logic for checking duplicate column into Util class and adding a test case for this --- .../sqlserver/jdbc/SQLServerDataTable.java | 20 +--------- .../com/microsoft/sqlserver/jdbc/TVP.java | 7 +--- .../com/microsoft/sqlserver/jdbc/Util.java | 39 ++++++++----------- .../jdbc/datatypes/TVPWithSqlVariantTest.java | 17 ++++++++ 4 files changed, 36 insertions(+), 47 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index 34fbd2314..60188841a 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -79,7 +79,7 @@ public synchronized Iterator> getIterator() { public synchronized void addColumnMetadata(String columnName, int sqlType) throws SQLServerException { // column names must be unique - checkDuplicateColumnName(columnName); + Util.checkDuplicateColumnName(columnName, columnNames); columnMetadata.put(columnCount++, new SQLServerDataColumn(columnName, sqlType)); } @@ -93,26 +93,10 @@ public synchronized void addColumnMetadata(String columnName, */ public synchronized void addColumnMetadata(SQLServerDataColumn column) throws SQLServerException { // column names must be unique - checkDuplicateColumnName(column.columnName); + Util.checkDuplicateColumnName(column.columnName, columnNames); columnMetadata.put(columnCount++, column); } - /** - * Checks if duplicate columns exists, in O(n) time. - * - * @param columnName - * the name of the column - * @throws SQLServerException - * when a duplicate column exists - */ - private void checkDuplicateColumnName(String columnName) throws SQLServerException { - //columnList.add will return false if the same column name already exists - if (!columnNames.add(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } /** * Adds one row of data to the data table. diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java index a99ee8a37..fa3d07dd6 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java @@ -189,12 +189,7 @@ void populateMetadataFromDataRecord() throws SQLServerException { throw new SQLServerException(SQLServerException.getErrString("R_TVPEmptyMetadata"), null); } for (int i = 0; i < sourceRecord.getColumnCount(); i++) { - //columnList.add will return false if the same column name already exists - if (!columnNames.add(sourceRecord.getColumnMetaData(i + 1).columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {sourceRecord.getColumnMetaData(i + 1).columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } + Util.checkDuplicateColumnName(sourceRecord.getColumnMetaData(i + 1).columnName, columnNames); // Make a copy here as we do not want to change user's metadata. SQLServerMetaData metaData = new SQLServerMetaData(sourceRecord.getColumnMetaData(i + 1)); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java index ad43f0f74..c1d6d81dc 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; +import java.util.Set; import java.util.UUID; import java.util.logging.Level; import java.util.logging.LogManager; @@ -557,32 +558,24 @@ static String escapeSQLId(String inID) { outID.append(']'); return outID.toString(); } - - /* + + /** + * Checks if duplicate columns exists, in O(n) time. + * + * @param columnName + * the name of the column + * @throws SQLServerException + * when a duplicate column exists + */ static void checkDuplicateColumnName(String columnName, - Map columnMetadata) throws SQLServerException { - if (columnMetadata.get(0) instanceof SQLServerMetaData) { - for (Entry entry : columnMetadata.entrySet()) { - SQLServerMetaData value = (SQLServerMetaData) entry.getValue(); - if (value.columnName.equals(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } - } - else if (columnMetadata.get(0) instanceof SQLServerDataColumn) { - for (Entry entry : columnMetadata.entrySet()) { - SQLServerDataColumn value = (SQLServerDataColumn) entry.getValue(); - if (value.columnName.equals(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } + Set columnNames) throws SQLServerException { + //columnList.add will return false if the same column name already exists + if (!columnNames.add(columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); } } - */ /** * Reads a UNICODE string from byte buffer at offset (up to byteLength). diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java index da20156c7..2e1fe11f6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -378,6 +378,23 @@ public void testIntStoredProcedure() throws SQLServerException { Cstatement.close(); } } + + /** + * Test for allowing duplicate columns + * + * @throws SQLServerException + */ + @Test + public void testDuplicateColumn() throws SQLServerException { + tvp = new SQLServerDataTable(); + tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); + tvp.addColumnMetadata("c2", microsoft.sql.Types.SQL_VARIANT); + try { + tvp.addColumnMetadata("c2", microsoft.sql.Types.SQL_VARIANT); + } catch (SQLServerException e) { + assertEquals(e.getMessage(), "A column name c2 already belongs to this SQLServerDataTable."); + } + } private static String[] createNumericValues() { Boolean C1_BIT; From 4b93851adfb05efc7cf5e05a6dab59fdf6395ea1 Mon Sep 17 00:00:00 2001 From: Jamie Magee Date: Tue, 10 Oct 2017 10:01:14 +0000 Subject: [PATCH 43/68] Remove explicit interface reference --- .../microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java index 425d741bf..813d3e7ea 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java @@ -788,7 +788,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return ParameterMetaData.parameterModeUnknown; + return parameterModeUnknown; } } @@ -908,7 +908,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return ParameterMetaData.parameterNoNulls; + return parameterNoNulls; } } From eb7efe3ea3a94b3a4a0be6c10d6e45c1aaf9b408 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Tue, 10 Oct 2017 11:10:08 -0700 Subject: [PATCH 44/68] Modified bvtTests to be able to test resultSet closing explicitly. --- .../microsoft/sqlserver/jdbc/bvt/bvtTest.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java index 90ba5d0ac..eaad85365 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java @@ -361,10 +361,11 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { try (DBConnection conn = new DBConnection(connectionString); DBStatement stmt1 = conn.createStatement(); - DBStatement stmt2 = conn.createStatement(); - DBResultSet rs1 = stmt1.executeQuery(query); - DBResultSet rs2 = stmt2.executeQuery(query2)) { + DBStatement stmt2 = conn.createStatement()) { + DBResultSet rs1 = stmt1.executeQuery(query); + DBResultSet rs2 = stmt2.executeQuery(query2); + // Interleave resultset calls rs1.next(); rs1.verifyCurrentRow(table1); @@ -373,8 +374,10 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { rs1.next(); rs1.verifyCurrentRow(table1); rs1.verify(table1); + rs1.close(); rs2.next(); rs2.verify(table2); + rs2.close(); } } @@ -390,10 +393,10 @@ public void testTwoResultsetsSameStmt() throws SQLException { String query2 = "SELECT * FROM " + table2.getEscapedTableName(); try (DBConnection conn = new DBConnection(connectionString); - DBStatement stmt = conn.createStatement(); - DBResultSet rs1 = stmt.executeQuery(query); - DBResultSet rs2 = stmt.executeQuery(query2)) { + DBStatement stmt = conn.createStatement()) { + DBResultSet rs1 = stmt.executeQuery(query); + DBResultSet rs2 = stmt.executeQuery(query2); // Interleave resultset calls. rs is expected to be closed try { rs1.next(); @@ -409,8 +412,10 @@ public void testTwoResultsetsSameStmt() throws SQLException { catch (SQLException e) { assertEquals(e.toString(), "com.microsoft.sqlserver.jdbc.SQLServerException: The result set is closed."); } + rs1.close(); rs2.next(); rs2.verify(table2); + rs2.close(); } } From 92aa789803afb434c0af0da1b047e4d03ad58f87 Mon Sep 17 00:00:00 2001 From: Pinky Date: Mon, 16 Oct 2017 21:35:08 +0800 Subject: [PATCH 45/68] updates gradle dependencies --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index e648bff70..5cc29b949 100644 --- a/build.gradle +++ b/build.gradle @@ -66,7 +66,7 @@ repositories { } dependencies { - compile 'com.microsoft.azure:azure-keyvault:0.9.7', + compile 'com.microsoft.azure:azure-keyvault:1.0.0', 'com.microsoft.azure:adal4j:1.1.3' testCompile 'junit:junit:4.12', From 94ae4bf6329688d5dfcbf413617857a4145e33e5 Mon Sep 17 00:00:00 2001 From: ulvii Date: Wed, 18 Oct 2017 14:54:24 -0700 Subject: [PATCH 46/68] 6.3.4 release (#528) * 6.3.4-preview release --- CHANGELOG.md | 14 ++++++++++++++ README.md | 4 ++-- pom.xml | 2 +- .../microsoft/sqlserver/jdbc/SQLJdbcVersion.java | 2 +- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e909a89d..0fe6a5717 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## [6.3.4] Preview Release +### Added +- Added new ThreadGroup creation to prevent IllegalThreadStateException if the underlying ThreadGroup has been destroyed. [#474](https://github.com/Microsoft/mssql-jdbc/pull/474) +- Added try-with-resources to JUnit tests [#520](https://github.com/Microsoft/mssql-jdbc/pull/520) + +### Fixed Issues +- Fixed the issue with passing parameters names that start with '@' to a CallableStatement [#495](https://github.com/Microsoft/mssql-jdbc/pull/495) +- Fixed SQLServerDataTable creation being O(n^2) issue [#514](https://github.com/Microsoft/mssql-jdbc/pull/514) + +### Changed +- Changed some manual array copying to System.arraycopy() [#500](https://github.com/Microsoft/mssql-jdbc/pull/500) +- Removed redundant toString() on String objects [#501](https://github.com/Microsoft/mssql-jdbc/pull/501) +- Replaced literals with constants [#502](https://github.com/Microsoft/mssql-jdbc/pull/502) + ## [6.3.3] Preview Release ### Added - Added connection properties for specifying custom TrustManager [#74](https://github.com/Microsoft/mssql-jdbc/pull/74) diff --git a/README.md b/README.md index 2196f02d4..1edeca9e1 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ To get the latest preview version of the driver, add the following to your POM f com.microsoft.sqlserver mssql-jdbc - 6.3.3.jre8-preview + 6.3.4.jre8-preview ``` @@ -120,7 +120,7 @@ Projects that require either of the two features need to explicitly declare the com.microsoft.sqlserver mssql-jdbc - 6.3.3.jre8-preview + 6.3.4.jre8-preview compile diff --git a/pom.xml b/pom.xml index 296eb209e..8c39911c9 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.4-SNAPSHOT + 6.3.4 jar diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java index 9c9f7b691..2aa091ff0 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java @@ -11,6 +11,6 @@ final class SQLJdbcVersion { static final int major = 6; static final int minor = 3; - static final int patch = 3; + static final int patch = 4; static final int build = 0; } From 16a76c7f42490501e531fa6234dd7572467a325e Mon Sep 17 00:00:00 2001 From: ulvii Date: Thu, 19 Oct 2017 12:13:09 -0700 Subject: [PATCH 47/68] Merge dev to master for 6.3.4-preview release (#529) * TimeoutTimer: Check for destroyed TheadGroup Running a query that uses a timer can cause an IllegalThreadStateException if the underlying ThreadGroup has been destroyed * TimeoutTimer: Forgot reference Forgot to add AtomicReference * recognize CallableStatement parameter names with leading '@' * Replace manual array copy Replace manual array copying with System.arraycopy(). * Remove redundant String.toString() Calling toString() on a String object is redundant * Replace bare literals Replace bare literals with magic constants. For example: `cal.set(1, 1, 577738, 0, 0, 0);` becomes `cal.set(1, Calendar.FEBRUARY, 577738, 0, 0, 0);` * cleanup tables after test * more cleaning of tables and procedures * Implement checkDuplicateColumnName to check duplicate columns * Revert "Implement checkDuplicateColumnName to check duplicate columns" This reverts commit e77a046c55097c71f9ce063c8ee603480f7576ac. * Revert "Revert "Implement checkDuplicateColumnName to check duplicate columns"" This reverts commit 8f69956400134ad0e10aadc94ed2eb5dee9ef980. * Apply same logic for TVP * use try with resources * add another try-with-resource * drop a not needed method * try-with-resources implementation commit 1 * Update .travis.yml Updated docker image tag for mssql-server-linux * Update .travis.yml Updating docker run command as well. * Fix AESetup issue with dropCEK * try-with-resources implementation commit 2 * avoid creating connection for termination * remove null check and change Set object name * tweak to preserve original parameter name for exception message * Refactoring the logic for checking duplicate column into Util class and adding a test case for this * Remove explicit interface reference * Modified bvtTests to be able to test resultSet closing explicitly. * 6.3.4 release (#528) * 6.3.4-preview release --- CHANGELOG.md | 14 + README.md | 4 +- pom.xml | 2 +- .../com/microsoft/sqlserver/jdbc/DDC.java | 4 +- .../microsoft/sqlserver/jdbc/IOBuffer.java | 21 +- .../sqlserver/jdbc/SQLJdbcVersion.java | 2 +- .../sqlserver/jdbc/SQLServerBulkCopy.java | 2 +- .../jdbc/SQLServerBulkCopy42Helper.java | 2 +- .../jdbc/SQLServerCallableStatement.java | 13 +- .../sqlserver/jdbc/SQLServerConnection.java | 4 +- .../sqlserver/jdbc/SQLServerDataTable.java | 9 +- .../jdbc/SQLServerParameterMetaData.java | 4 +- .../jdbc/SQLServerPreparedStatement.java | 6 +- .../com/microsoft/sqlserver/jdbc/TVP.java | 7 +- .../com/microsoft/sqlserver/jdbc/Util.java | 37 +- .../jdbc/AlwaysEncrypted/AESetup.java | 2227 ++++++++--------- .../CallableStatementTest.java | 576 ++--- .../JDBCEncryptionDecryptionTest.java | 113 +- .../AlwaysEncrypted/PrecisionScaleTest.java | 422 ++-- .../jdbc/bulkCopy/BulkCopyAllTypes.java | 72 +- .../jdbc/bulkCopy/BulkCopyCSVTest.java | 133 +- .../bulkCopy/BulkCopyColumnMappingTest.java | 51 +- .../jdbc/bulkCopy/BulkCopyConnectionTest.java | 23 +- .../BulkCopyISQLServerBulkRecordTest.java | 45 +- .../bulkCopy/BulkCopyResultSetCursorTest.java | 257 +- .../jdbc/bulkCopy/BulkCopyTestSetUp.java | 31 +- .../jdbc/bulkCopy/BulkCopyTestUtil.java | 417 ++- .../jdbc/bulkCopy/BulkCopyTimeoutTest.java | 26 +- .../ISQLServerBulkRecordIssuesTest.java | 61 +- .../microsoft/sqlserver/jdbc/bvt/bvtTest.java | 315 +-- .../sqlserver/jdbc/bvt/bvtTestSetup.java | 17 +- .../CallableStatementTest.java | 113 +- .../jdbc/connection/ConnectionDriverTest.java | 160 +- .../jdbc/connection/DBMetadataTest.java | 35 +- .../connection/NativeMSSQLDataSourceTest.java | 49 +- .../jdbc/connection/PoolingTest.java | 28 +- .../jdbc/datatypes/TVPWithSqlVariantTest.java | 17 + .../unit/statement/CallableMixedTest.java | 95 +- .../jdbc/unit/statement/LimitEscapeTest.java | 12 +- .../jdbc/unit/statement/MergeTest.java | 52 +- .../statement/NamedParamMultiPartTest.java | 106 +- .../jdbc/unit/statement/PQImpsTest.java | 22 +- .../jdbc/unit/statement/PoolableTest.java | 73 +- .../jdbc/unit/statement/StatementTest.java | 481 ++-- .../sqlserver/testframework/DBConnection.java | 2 +- .../sqlserver/testframework/DBResultSet.java | 2 +- .../sqlserver/testframework/DBStatement.java | 4 +- 47 files changed, 2822 insertions(+), 3346 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e909a89d..0fe6a5717 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## [6.3.4] Preview Release +### Added +- Added new ThreadGroup creation to prevent IllegalThreadStateException if the underlying ThreadGroup has been destroyed. [#474](https://github.com/Microsoft/mssql-jdbc/pull/474) +- Added try-with-resources to JUnit tests [#520](https://github.com/Microsoft/mssql-jdbc/pull/520) + +### Fixed Issues +- Fixed the issue with passing parameters names that start with '@' to a CallableStatement [#495](https://github.com/Microsoft/mssql-jdbc/pull/495) +- Fixed SQLServerDataTable creation being O(n^2) issue [#514](https://github.com/Microsoft/mssql-jdbc/pull/514) + +### Changed +- Changed some manual array copying to System.arraycopy() [#500](https://github.com/Microsoft/mssql-jdbc/pull/500) +- Removed redundant toString() on String objects [#501](https://github.com/Microsoft/mssql-jdbc/pull/501) +- Replaced literals with constants [#502](https://github.com/Microsoft/mssql-jdbc/pull/502) + ## [6.3.3] Preview Release ### Added - Added connection properties for specifying custom TrustManager [#74](https://github.com/Microsoft/mssql-jdbc/pull/74) diff --git a/README.md b/README.md index 2196f02d4..1edeca9e1 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ To get the latest preview version of the driver, add the following to your POM f com.microsoft.sqlserver mssql-jdbc - 6.3.3.jre8-preview + 6.3.4.jre8-preview ``` @@ -120,7 +120,7 @@ Projects that require either of the two features need to explicitly declare the com.microsoft.sqlserver mssql-jdbc - 6.3.3.jre8-preview + 6.3.4.jre8-preview compile diff --git a/pom.xml b/pom.xml index 296eb209e..8c39911c9 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.4-SNAPSHOT + 6.3.4 jar diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java index 6bf3af9e6..77891c37b 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java @@ -439,9 +439,7 @@ private static byte[] convertToBytes(BigDecimal value, } } int offset = numBytes - unscaledBytes.length; - for (int i = offset; i < numBytes; ++i) { - ret[i] = unscaledBytes[i - offset]; - } + System.arraycopy(unscaledBytes, offset - offset, ret, offset, numBytes - offset); return ret; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index 4369d3c00..d87a9cb14 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -64,6 +64,7 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; @@ -498,7 +499,7 @@ class GregorianChange { GregorianCalendar cal = new GregorianCalendar(Locale.US); cal.clear(); - cal.set(1, 1, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582) + cal.set(1, Calendar.FEBRUARY, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582) if (cal.get(Calendar.DAY_OF_MONTH) == 15) { // If the date calculation is correct(the above bug is fixed), // post the default gregorian cut over date, the pure gregorian date @@ -4828,7 +4829,7 @@ private void writeInternalTVPRowValues(JDBCType jdbcType, else { if (isSqlVariant) { writeTVPSqlVariantHeader(10, TDSType.FLOAT8.byteValue(), (byte) 0); - writeDouble(Double.valueOf(currentColumnStringValue.toString())); + writeDouble(Double.valueOf(currentColumnStringValue)); break; } writeByte((byte) 8); // len of data bytes @@ -7119,13 +7120,21 @@ final class TimeoutTimer implements Runnable { private volatile Future task; private static final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { - private final ThreadGroup tg = new ThreadGroup(threadGroupName); - private final String threadNamePrefix = tg.getName() + "-"; + private final AtomicReference tgr = new AtomicReference<>(); private final AtomicInteger threadNumber = new AtomicInteger(0); @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(tg, r, threadNamePrefix + threadNumber.incrementAndGet()); + public Thread newThread(Runnable r) + { + ThreadGroup tg = tgr.get(); + + if (tg == null || tg.isDestroyed()) + { + tg = new ThreadGroup(threadGroupName); + tgr.set(tg); + } + + Thread t = new Thread(tg, r, tg.getName() + "-" + threadNumber.incrementAndGet()); t.setDaemon(true); return t; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java index 9c9f7b691..2aa091ff0 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java @@ -11,6 +11,6 @@ final class SQLJdbcVersion { static final int major = 6; static final int minor = 3; - static final int patch = 3; + static final int patch = 4; static final int build = 0; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java index 14e4338b3..a383e1946 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java @@ -1521,7 +1521,7 @@ private String createInsertBulkCommand(TDSWriter tdsWriter) throws SQLServerExce if (it.hasNext()) { bulkCmd.append(" with ("); while (it.hasNext()) { - bulkCmd.append(it.next().toString()); + bulkCmd.append(it.next()); if (it.hasNext()) { bulkCmd.append(", "); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java index ec44c1834..ea9ff510f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java @@ -75,7 +75,7 @@ static Object getTemporalObjectFromCSVWithFormatter(String valueStrUntrimmed, return ts; case java.sql.Types.TIME: // Time is returned as Timestamp to preserve nano seconds. - cal.set(connection.baseYear(), 00, 01); + cal.set(connection.baseYear(), Calendar.JANUARY, 01); ts = new java.sql.Timestamp(cal.getTimeInMillis()); ts.setNanos(taNano); return new java.sql.Timestamp(ts.getTime()); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java index 40a77be15..5ad8689c8 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java @@ -1451,6 +1451,15 @@ public NClob getNClob(String parameterName) throws SQLException { if (paramNames != null) l = paramNames.size(); + // handle `@name` as well as `name`, since `@name` is what's returned + // by DatabaseMetaData#getProcedureColumns + String columnNameWithoutAtSign = null; + if (columnName.startsWith("@")) { + columnNameWithoutAtSign = columnName.substring(1, columnName.length()); + } else { + columnNameWithoutAtSign = columnName; + } + // In order to be as accurate as possible when locating parameter name // indexes, as well as be deterministic when running on various client // locales, we search for parameter names using the following scheme: @@ -1465,7 +1474,7 @@ public NClob getNClob(String parameterName) throws SQLException { for (i = 0; i < l; i++) { String sParam = paramNames.get(i); sParam = sParam.substring(1, sParam.length()); - if (sParam.equals(columnName)) { + if (sParam.equals(columnNameWithoutAtSign)) { matchPos = i; break; } @@ -1477,7 +1486,7 @@ public NClob getNClob(String parameterName) throws SQLException { for (i = 0; i < l; i++) { String sParam = paramNames.get(i); sParam = sParam.substring(1, sParam.length()); - if (sParam.equalsIgnoreCase(columnName)) { + if (sParam.equalsIgnoreCase(columnNameWithoutAtSign)) { matchPos = i; break; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 730f13bf7..a8397b605 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -1717,7 +1717,7 @@ else if (0 == requestedPacketSize) sPropKey = SQLServerDriverStringProperty.SSL_PROTOCOL.toString(); sPropValue = activeConnectionProperties.getProperty(sPropKey); if (null == sPropValue) { - sPropValue = SQLServerDriverStringProperty.SSL_PROTOCOL.getDefaultValue().toString(); + sPropValue = SQLServerDriverStringProperty.SSL_PROTOCOL.getDefaultValue(); activeConnectionProperties.setProperty(sPropKey, sPropValue); } else { @@ -5430,7 +5430,7 @@ String getInstancePort(String server, browserResult = new String(receiveBuffer, 3, receiveBuffer.length - 3); if (connectionlogger.isLoggable(Level.FINER)) connectionlogger.fine( - toString() + " Received SSRP UDP response from IP address: " + udpResponse.getAddress().getHostAddress().toString()); + toString() + " Received SSRP UDP response from IP address: " + udpResponse.getAddress().getHostAddress()); } catch (IOException ioException) { // Warn and retry diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index d3f176a31..60188841a 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -13,10 +13,12 @@ import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.UUID; public final class SQLServerDataTable { @@ -24,6 +26,7 @@ public final class SQLServerDataTable { int rowCount = 0; int columnCount = 0; Map columnMetadata = null; + Set columnNames = null; Map rows = null; private String tvpName = null; @@ -37,6 +40,7 @@ public final class SQLServerDataTable { // Name used in CREATE TYPE public SQLServerDataTable() throws SQLServerException { columnMetadata = new LinkedHashMap<>(); + columnNames = new HashSet<>(); rows = new HashMap<>(); } @@ -75,7 +79,7 @@ public synchronized Iterator> getIterator() { public synchronized void addColumnMetadata(String columnName, int sqlType) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(columnName, columnMetadata); + Util.checkDuplicateColumnName(columnName, columnNames); columnMetadata.put(columnCount++, new SQLServerDataColumn(columnName, sqlType)); } @@ -89,10 +93,11 @@ public synchronized void addColumnMetadata(String columnName, */ public synchronized void addColumnMetadata(SQLServerDataColumn column) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(column.columnName, columnMetadata); + Util.checkDuplicateColumnName(column.columnName, columnNames); columnMetadata.put(columnCount++, column); } + /** * Adds one row of data to the data table. * diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java index 1d11e61af..dca580ec9 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java @@ -793,7 +793,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + return parameterModeUnknown; } } @@ -913,7 +913,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + return parameterNoNulls; } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 1ba3c62e8..2437a82d0 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2503,8 +2503,7 @@ public long[] executeLargeBatch() throws SQLServerException, BatchUpdateExceptio updateCounts = new long[batchCommand.updateCounts.length]; - for (int i = 0; i < batchCommand.updateCounts.length; ++i) - updateCounts[i] = batchCommand.updateCounts[i]; + System.arraycopy(batchCommand.updateCounts, 0, updateCounts, 0, batchCommand.updateCounts.length); // Transform the SQLException into a BatchUpdateException with the update counts. if (null != batchCommand.batchException) { @@ -2571,8 +2570,7 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th // Fill in the parameter values for this batch Parameter paramValues[] = batchParamValues.get(numBatchesPrepared); assert paramValues.length == batchParam.length; - for (int i = 0; i < paramValues.length; i++) - batchParam[i] = paramValues[i]; + System.arraycopy(paramValues, 0, batchParam, 0, paramValues.length); boolean hasExistingTypeDefinitions = preparedTypeDefinitions != null; boolean hasNewTypeDefinitions = buildPreparedStrings(batchParam, false); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java index 6f68d685a..fa3d07dd6 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java @@ -12,10 +12,12 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.MessageFormat; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; enum TVPType { ResultSet, @@ -48,6 +50,7 @@ class TVP { Iterator> sourceDataTableRowIterator = null; ISQLServerDataRecord sourceRecord = null; TVPType tvpType = null; + Set columnNames = null; // MultiPartIdentifierState enum MPIState { @@ -94,6 +97,7 @@ void initTVP(TVPType type, ISQLServerDataRecord tvpRecord) throws SQLServerException { initTVP(TVPType.ISQLServerDataRecord, tvpPartName); sourceRecord = tvpRecord; + columnNames = new HashSet<>(); // Populate TVP metdata from ISQLServerDataRecord. populateMetadataFromDataRecord(); @@ -185,8 +189,9 @@ void populateMetadataFromDataRecord() throws SQLServerException { throw new SQLServerException(SQLServerException.getErrString("R_TVPEmptyMetadata"), null); } for (int i = 0; i < sourceRecord.getColumnCount(); i++) { + Util.checkDuplicateColumnName(sourceRecord.getColumnMetaData(i + 1).columnName, columnNames); + // Make a copy here as we do not want to change user's metadata. - Util.checkDuplicateColumnName(sourceRecord.getColumnMetaData(i + 1).columnName, columnMetadata); SQLServerMetaData metaData = new SQLServerMetaData(sourceRecord.getColumnMetaData(i + 1)); columnMetadata.put(i, metaData); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java index db10ebce1..c1d6d81dc 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; +import java.util.Set; import java.util.UUID; import java.util.logging.Level; import java.util.logging.LogManager; @@ -557,28 +558,22 @@ static String escapeSQLId(String inID) { outID.append(']'); return outID.toString(); } - + + /** + * Checks if duplicate columns exists, in O(n) time. + * + * @param columnName + * the name of the column + * @throws SQLServerException + * when a duplicate column exists + */ static void checkDuplicateColumnName(String columnName, - Map columnMetadata) throws SQLServerException { - if (columnMetadata.get(0) instanceof SQLServerMetaData) { - for (Entry entry : columnMetadata.entrySet()) { - SQLServerMetaData value = (SQLServerMetaData) entry.getValue(); - if (value.columnName.equals(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } - } - else if (columnMetadata.get(0) instanceof SQLServerDataColumn) { - for (Entry entry : columnMetadata.entrySet()) { - SQLServerDataColumn value = (SQLServerDataColumn) entry.getValue(); - if (value.columnName.equals(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } + Set columnNames) throws SQLServerException { + //columnList.add will return false if the same column name already exists + if (!columnNames.add(columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java index 6fc795a98..9ae2445c1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -80,8 +80,6 @@ public class AESetup extends AbstractTest { static SQLServerColumnEncryptionKeyStoreProvider storeProvider = null; static SQLServerStatementColumnEncryptionSetting stmtColEncSetting = null; - private static SQLServerPreparedStatement pstmt = null; - /** * Create connection, statement and generate path of resource file * @@ -94,26 +92,28 @@ static void setUpConnection() throws TestAbortedException, Exception { "Aborting test case as SQL Server version is not compatible with Always encrypted "); String AETestConenctionString = connectionString + ";sendTimeAsDateTime=false"; - readFromFile(javaKeyStoreInputFile, "Alias name"); - con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); - stmt = (SQLServerStatement) con.createStatement(); - dropCEK(); - dropCMK(); - con.close(); - + + try(SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropCEK(stmt); + dropCMK(stmt); + } + keyPath = Utils.getCurrentClassPath() + jksName; storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, secretstrJks.toCharArray()); stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.Enabled; + Properties info = new Properties(); info.setProperty("ColumnEncryptionSetting", "Enabled"); info.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); info.setProperty("keyStoreLocation", keyPath); info.setProperty("keyStoreSecret", secretstrJks); + con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString, info); stmt = (SQLServerStatement) con.createStatement(); createCMK(keyStoreName, javaKeyAliases); - createCEK(storeProvider); + createCEK(storeProvider); } /** @@ -126,8 +126,8 @@ static void setUpConnection() throws TestAbortedException, Exception { @AfterAll private static void dropAll() throws SQLServerException, SQLException { dropTables(stmt); - dropCEK(); - dropCMK(); + dropCEK(stmt); + dropCMK(stmt); Util.close(null, stmt, con); } @@ -140,33 +140,26 @@ private static void dropAll() throws SQLServerException, SQLException { */ private static void readFromFile(String inputFile, String lookupValue) throws IOException { - BufferedReader buffer = null; filePath = Utils.getCurrentClassPath(); try { File f = new File(filePath + inputFile); assumeTrue(f.exists(), "Aborting test case since no java key store and alias name exists!"); - buffer = new BufferedReader(new FileReader(f)); - String readLine = ""; - String[] linecontents; - - while ((readLine = buffer.readLine()) != null) { - if (readLine.trim().contains(lookupValue)) { - linecontents = readLine.split(" "); - javaKeyAliases = linecontents[2]; - break; - } + try(BufferedReader buffer = new BufferedReader(new FileReader(f))) { + String readLine = ""; + String[] linecontents; + + while ((readLine = buffer.readLine()) != null) { + if (readLine.trim().contains(lookupValue)) { + linecontents = readLine.split(" "); + javaKeyAliases = linecontents[2]; + break; + } + } } - } catch (IOException e) { fail(e.toString()); } - finally { - if (null != buffer) { - buffer.close(); - } - } - } /** @@ -744,60 +737,60 @@ protected static void dropTables(SQLServerStatement statement) throws SQLExcepti protected static void populateBinaryNormalCase(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary20 - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(0)); - } - } - - // varbinary50 - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(1)); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(2)); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary20 + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(0)); + } + } + + // varbinary50 + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(1)); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(2)); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(3)); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(4)); + } + } + + pstmt.execute(); } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(3)); - } - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(4)); - } - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -809,60 +802,60 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th protected static void populateBinarySetObject(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary(20) - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(0)); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary(20) + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(0)); + } + } + + // varbinary(50) + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(1)); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(2)); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(3)); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(4)); + } + } + + pstmt.execute(); } - - // varbinary(50) - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(1)); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(2)); - } - } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(3)); - } - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(4)); - } - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -874,60 +867,60 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr protected static void populateBinarySetObjectWithJDBCType(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary(20) - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(0), JDBCType.BINARY); - } - } - - // varbinary(50) - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(1), JDBCType.VARBINARY); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(2), JDBCType.VARBINARY); - } - } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(3), JDBCType.BINARY); - } - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(4), JDBCType.VARBINARY); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary(20) + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(0), JDBCType.BINARY); + } + } + + // varbinary(50) + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(1), JDBCType.VARBINARY); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(2), JDBCType.VARBINARY); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(3), JDBCType.BINARY); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(4), JDBCType.VARBINARY); + } + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -938,30 +931,30 @@ protected static void populateBinarySetObjectWithJDBCType(LinkedList byt protected static void populateBinaryNullCase() throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.BINARY); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.BINARY); + } + + // varbinary, varbinary(max) + for (int i = 4; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.VARBINARY); + } + + // binary512 + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.BINARY); + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, java.sql.Types.VARBINARY); + } + + pstmt.execute(); } - - // varbinary, varbinary(max) - for (int i = 4; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.VARBINARY); - } - - // binary512 - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.BINARY); - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, java.sql.Types.VARBINARY); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -974,60 +967,60 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setString(i, charValues[0]); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setString(i, charValues[1]); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setString(i, charValues[2]); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setNString(i, charValues[3]); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setString(i, charValues[0]); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setString(i, charValues[1]); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setString(i, charValues[2]); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setNString(i, charValues[3]); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setNString(i, charValues[4]); + } + + // varchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setNString(i, charValues[5]); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + if (null == charValues[6]) { + pstmt.setUniqueIdentifier(i, null); + } + else { + pstmt.setUniqueIdentifier(i, uid); + } + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setString(i, charValues[7]); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setNString(i, charValues[8]); + } + + pstmt.execute(); } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setNString(i, charValues[4]); - } - - // varchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setNString(i, charValues[5]); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - if (null == charValues[6]) { - pstmt.setUniqueIdentifier(i, null); - } - else { - pstmt.setUniqueIdentifier(i, uid); - } - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setString(i, charValues[7]); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setNString(i, charValues[8]); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1040,55 +1033,55 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, charValues[0]); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, charValues[1]); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, charValues[2], java.sql.Types.LONGVARCHAR); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, charValues[0]); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, charValues[1]); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, charValues[2], java.sql.Types.LONGVARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, charValues[3], java.sql.Types.NCHAR); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, charValues[4], java.sql.Types.NCHAR); + } + + // nvarchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, charValues[5], java.sql.Types.LONGNVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, charValues[7]); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, charValues[8], java.sql.Types.NCHAR); + } + + pstmt.execute(); } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, charValues[3], java.sql.Types.NCHAR); - } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, charValues[4], java.sql.Types.NCHAR); - } - - // nvarchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, charValues[5], java.sql.Types.LONGNVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, charValues[7]); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, charValues[8], java.sql.Types.NCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1101,55 +1094,55 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, charValues[0], JDBCType.CHAR); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, charValues[1], JDBCType.VARCHAR); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, charValues[2], JDBCType.LONGVARCHAR); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, charValues[3], JDBCType.NCHAR); - } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, charValues[4], JDBCType.NVARCHAR); - } - - // nvarchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, charValues[5], JDBCType.LONGNVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, charValues[0], JDBCType.CHAR); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, charValues[1], JDBCType.VARCHAR); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, charValues[2], JDBCType.LONGVARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, charValues[3], JDBCType.NCHAR); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, charValues[4], JDBCType.NVARCHAR); + } + + // nvarchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, charValues[5], JDBCType.LONGNVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, charValues[7], JDBCType.VARCHAR); + } + + // vnarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, charValues[8], JDBCType.NVARCHAR); + } + + pstmt.execute(); } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, charValues[7], JDBCType.VARCHAR); - } - - // vnarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, charValues[8], JDBCType.NVARCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1161,46 +1154,46 @@ protected static void populateCharNullCase() throws SQLException { String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.CHAR); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.CHAR); + } + + // varchar, varchar(max) + for (int i = 4; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.VARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.NCHAR); + } + + // nvarchar, varchar(max) + for (int i = 13; i <= 18; i++) { + pstmt.setNull(i, java.sql.Types.NVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setNull(i, microsoft.sql.Types.GUID); + + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setNull(i, java.sql.Types.VARCHAR); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setNull(i, java.sql.Types.NVARCHAR); + } + + pstmt.execute(); } - - // varchar, varchar(max) - for (int i = 4; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.VARCHAR); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.NCHAR); - } - - // nvarchar, varchar(max) - for (int i = 13; i <= 18; i++) { - pstmt.setNull(i, java.sql.Types.NVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setNull(i, microsoft.sql.Types.GUID); - - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setNull(i, java.sql.Types.VARCHAR); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setNull(i, java.sql.Types.NVARCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1212,40 +1205,40 @@ protected static void populateCharNullCase() throws SQLException { protected static void populateDateNormalCase(LinkedList dateValues) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setDate(i, (Date) dateValues.get(0)); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setDate(i, (Date) dateValues.get(0)); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, (Time) dateValues.get(3)); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setDateTime(i, (Timestamp) dateValues.get(4)); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setSmallDateTime(i, (Timestamp) dateValues.get(5)); + } + + pstmt.execute(); } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, (Time) dateValues.get(3)); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setDateTime(i, (Timestamp) dateValues.get(4)); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setSmallDateTime(i, (Timestamp) dateValues.get(5)); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1257,25 +1250,25 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro protected static void populateDateScaleNormalCase(LinkedList dateValues) throws SQLException { String sql = "insert into " + scaleDateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(2) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); - } - - // time(2) - for (int i = 4; i <= 6; i++) { - pstmt.setTime(i, (Time) dateValues.get(5), 2); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(2) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); + } + + // time(2) + for (int i = 4; i <= 6; i++) { + pstmt.setTime(i, (Time) dateValues.get(5), 2); + } + + // datetimeoffset(2) + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); + } + + pstmt.execute(); } - - // datetimeoffset(2) - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1293,60 +1286,60 @@ protected static void populateDateSetObject(LinkedList dateValues, String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Date) dateValues.get(0), java.sql.Types.DATE); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Date) dateValues.get(0), JDBCType.DATE); - else - pstmt.setObject(i, (Date) dateValues.get(0)); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Timestamp) dateValues.get(1), java.sql.Types.TIMESTAMP); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Timestamp) dateValues.get(1), JDBCType.TIMESTAMP); - else - pstmt.setObject(i, (Timestamp) dateValues.get(1)); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); - else - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2)); - } - - // time default - for (int i = 10; i <= 12; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Time) dateValues.get(3), java.sql.Types.TIME); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Time) dateValues.get(3), JDBCType.TIME); - else - pstmt.setObject(i, (Time) dateValues.get(3)); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, (Timestamp) dateValues.get(4), microsoft.sql.Types.DATETIME); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Date) dateValues.get(0), java.sql.Types.DATE); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Date) dateValues.get(0), JDBCType.DATE); + else + pstmt.setObject(i, (Date) dateValues.get(0)); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Timestamp) dateValues.get(1), java.sql.Types.TIMESTAMP); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Timestamp) dateValues.get(1), JDBCType.TIMESTAMP); + else + pstmt.setObject(i, (Timestamp) dateValues.get(1)); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); + else + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2)); + } + + // time default + for (int i = 10; i <= 12; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Time) dateValues.get(3), java.sql.Types.TIME); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Time) dateValues.get(3), JDBCType.TIME); + else + pstmt.setObject(i, (Time) dateValues.get(3)); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, (Timestamp) dateValues.get(4), microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, (Timestamp) dateValues.get(5), microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, (Timestamp) dateValues.get(5), microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1357,40 +1350,40 @@ else if (setter.equalsIgnoreCase("setwithJDBCType")) protected void populateDateSetObjectNull() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.DATE); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.DATE); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIME); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1401,40 +1394,40 @@ protected void populateDateSetObjectNull() throws SQLException { protected static void populateDateNullCase() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.DATE); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.DATE); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setNull(i, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setNull(i, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.TIME); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setNull(i, microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setNull(i, java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setNull(i, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.TIME); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, microsoft.sql.Types.DATETIME); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setNull(i, microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1447,101 +1440,101 @@ protected static void populateNumeric(String[] values) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setShort(i, Short.valueOf(values[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setShort(i, Short.valueOf(values[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setInt(i, Integer.valueOf(values[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setLong(i, Long.valueOf(values[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.valueOf(values[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.valueOf(values[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.valueOf(values[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (values[8].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(values[8]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (values[10].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(values[10]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[11]), 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, new BigDecimal(values[12])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setShort(i, Short.valueOf(values[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setShort(i, Short.valueOf(values[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setInt(i, Integer.valueOf(values[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setLong(i, Long.valueOf(values[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.valueOf(values[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.valueOf(values[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.valueOf(values[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (values[8].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(values[8]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (values[10].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(values[10]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[11]), 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, new BigDecimal(values[12])); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setMoney(i, new BigDecimal(values[13])); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[14]), 28, 4); + } + + // numeric(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[15]), 28, 4); + } + + pstmt.execute(); } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setMoney(i, new BigDecimal(values[13])); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[14]), 28, 4); - } - - // numeric(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[15]), 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1554,101 +1547,101 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setObject(i, true); - } - else { - pstmt.setObject(i, false); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setObject(i, true); + } + else { + pstmt.setObject(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, Short.valueOf(values[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, Short.valueOf(values[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, Integer.valueOf(values[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, Long.valueOf(values[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, Double.valueOf(values[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, Double.valueOf(values[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, Float.valueOf(values[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, Short.valueOf(values[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, Short.valueOf(values[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, Integer.valueOf(values[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, Long.valueOf(values[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, Double.valueOf(values[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, Double.valueOf(values[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, Float.valueOf(values[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1661,101 +1654,101 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setObject(i, true); - } - else { - pstmt.setObject(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, Short.valueOf(values[1]), JDBCType.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, Short.valueOf(values[2]), JDBCType.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, Integer.valueOf(values[3]), JDBCType.INTEGER); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setObject(i, true); + } + else { + pstmt.setObject(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, Short.valueOf(values[1]), JDBCType.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, Short.valueOf(values[2]), JDBCType.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, Integer.valueOf(values[3]), JDBCType.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, Long.valueOf(values[4]), JDBCType.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, Double.valueOf(values[5]), JDBCType.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, Double.valueOf(values[6]), JDBCType.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, Float.valueOf(values[7]), JDBCType.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, Long.valueOf(values[4]), JDBCType.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, Double.valueOf(values[5]), JDBCType.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, Double.valueOf(values[6]), JDBCType.DOUBLE); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, Float.valueOf(values[7]), JDBCType.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1767,90 +1760,90 @@ protected static void populateNumericSetObjectNull() throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.BIT); - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, java.sql.Types.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.INTEGER); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, java.sql.Types.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.BIT); + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, java.sql.Types.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, java.sql.Types.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, null, java.sql.Types.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, null, java.sql.Types.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1865,89 +1858,89 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.BIT); - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setNull(i, java.sql.Types.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.INTEGER); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, java.sql.Types.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setNull(i, java.sql.Types.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setNull(i, java.sql.Types.DOUBLE); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setNull(i, java.sql.Types.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setBigDecimal(i, null); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, null, 10, 5); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.BIT); + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setNull(i, java.sql.Types.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, java.sql.Types.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setNull(i, java.sql.Types.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setNull(i, java.sql.Types.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setNull(i, java.sql.Types.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setBigDecimal(i, null); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, null, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setBigDecimal(i, null); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, null, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, null); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setMoney(i, null); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, null, 28, 4); + } + + // decimal(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, null, 28, 4); + } + pstmt.execute(); } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setBigDecimal(i, null); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, null, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, null); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setMoney(i, null); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, null, 28, 4); - } - - // decimal(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, null, 28, 4); - } - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1962,105 +1955,105 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - if (1 == Integer.valueOf(numericValues[1])) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // smallint - for (int i = 7; i <= 9; i++) { - if (numericValues[2].equalsIgnoreCase("255")) { - pstmt.setByte(i, (byte) 255); - } - else { - pstmt.setByte(i, Byte.valueOf(numericValues[2])); - } - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setShort(i, Short.valueOf(numericValues[3])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (numericValues[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + if (1 == Integer.valueOf(numericValues[1])) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // smallint + for (int i = 7; i <= 9; i++) { + if (numericValues[2].equalsIgnoreCase("255")) { + pstmt.setByte(i, (byte) 255); + } + else { + pstmt.setByte(i, Byte.valueOf(numericValues[2])); + } + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setShort(i, Short.valueOf(numericValues[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setInt(i, Integer.valueOf(numericValues[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.valueOf(numericValues[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.valueOf(numericValues[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.valueOf(numericValues[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[13])); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + } + + pstmt.execute(); } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setInt(i, Integer.valueOf(numericValues[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.valueOf(numericValues[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.valueOf(numericValues[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.valueOf(numericValues[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[13])); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -2069,7 +2062,7 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S * @throws SQLServerException * @throws SQLException */ - private static void dropCEK() throws SQLServerException, SQLException { + private static void dropCEK(SQLServerStatement stmt) throws SQLServerException, SQLException { String cekSql = " if exists (SELECT name from sys.column_encryption_keys where name='" + cekName + "')" + " begin" + " drop column encryption key " + cekName + " end"; stmt.execute(cekSql); @@ -2081,7 +2074,7 @@ private static void dropCEK() throws SQLServerException, SQLException { * @throws SQLServerException * @throws SQLException */ - private static void dropCMK() throws SQLServerException, SQLException { + private static void dropCMK(SQLServerStatement stmt) throws SQLServerException, SQLException { String cekSql = " if exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')" + " begin" + " drop column master key " + cmkName + " end"; stmt.execute(cekSql); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java index 9c23e98c1..cc6a67e29 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -42,9 +42,6 @@ @RunWith(JUnitPlatform.class) public class CallableStatementTest extends AESetup { - private static SQLServerPreparedStatement pstmt = null; - private static SQLServerCallableStatement callableStatement = null; - private static String multiStatementsProcedure = "multiStatementsProcedure"; private static String inputProcedure = "inputProcedure"; @@ -470,118 +467,120 @@ private static void createTables() throws SQLException { private static void populateTable4() throws SQLException { String sql = "insert into " + table4 + " values( " + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + + pstmt.execute(); } - - pstmt.execute(); } private static void populateTable3() throws SQLException { String sql = "insert into " + table3 + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setShort(i, Short.valueOf(numericValues[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setShort(i, Short.parseShort(numericValues[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setLong(i, Long.parseLong(numericValues[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.parseDouble(numericValues[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.parseDouble(numericValues[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.parseFloat(numericValues[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (numericValues[8].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (numericValues[10].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); - } - - // int2 - for (int i = 37; i <= 39; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); - } - // smallmoney - for (int i = 40; i <= 42; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); - } - - // money - for (int i = 43; i <= 45; i++) { - pstmt.setMoney(i, new BigDecimal(numericValues[13])); - } - - // decimal(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); - } - - // numeric(28,4) - for (int i = 49; i <= 51; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (numericValues[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setShort(i, Short.valueOf(numericValues[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setShort(i, Short.parseShort(numericValues[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setLong(i, Long.parseLong(numericValues[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.parseDouble(numericValues[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.parseDouble(numericValues[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.parseFloat(numericValues[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (numericValues[8].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (numericValues[10].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); + } + + // int2 + for (int i = 37; i <= 39; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + // smallmoney + for (int i = 40; i <= 42; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); + } + + // money + for (int i = 43; i <= 45; i++) { + pstmt.setMoney(i, new BigDecimal(numericValues[13])); + } + + // decimal(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); + } + + // numeric(28,4) + for (int i = 49; i <= 51; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + } + + pstmt.execute(); } - - pstmt.execute(); } private void createMultiInsertionSelection() throws SQLException { @@ -600,44 +599,39 @@ private void MultiInsertionSelection() throws SQLException { try { String sql = "{call " + multiStatementsProcedure + " (?,?,?,?,?,?)}"; - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - - // char, varchar - for (int i = 1; i <= 3; i++) { - callableStatement.setString(i, charValues[0]); - } - - for (int i = 4; i <= 6; i++) { - callableStatement.setString(i, charValues[1]); - } - - boolean results = callableStatement.execute(); - - // skip update count which is given by insertion - while (false == results && (-1) != callableStatement.getUpdateCount()) { - results = callableStatement.getMoreResults(); - } - - while (results) { - rs = callableStatement.getResultSet(); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns); - } - rs.close(); - results = callableStatement.getMoreResults(); + try(SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { + + // char, varchar + for (int i = 1; i <= 3; i++) { + callableStatement.setString(i, charValues[0]); + } + + for (int i = 4; i <= 6; i++) { + callableStatement.setString(i, charValues[1]); + } + + boolean results = callableStatement.execute(); + + // skip update count which is given by insertion + while (false == results && (-1) != callableStatement.getUpdateCount()) { + results = callableStatement.getMoreResults(); + } + + while (results) { + try(ResultSet rs = callableStatement.getResultSet()) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + while (rs.next()) { + testGetString(rs, numberOfColumns); + } + } + results = callableStatement.getMoreResults(); + } } } catch (SQLException e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testGetString(ResultSet rs, @@ -675,8 +669,7 @@ private void createInputProcedure() throws SQLException { private void testInputProcedure(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(values[3])); if (RandomData.returnZero) @@ -703,19 +696,14 @@ private void testInputProcedure(String sql, callableStatement.setBigDecimal(14, new BigDecimal(values[14]), 28, 4); callableStatement.setBigDecimal(15, new BigDecimal(values[15]), 28, 4); - SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery(); - rs.next(); - - assertEquals(rs.getString(1), values[3], "" + "Test for input parameter fails.\n"); + try (SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery()) { + rs.next(); + assertEquals(rs.getString(1), values[3], "" + "Test for input parameter fails.\n"); + } } catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createInputProcedure2() throws SQLException { @@ -735,8 +723,7 @@ private void createInputProcedure2() throws SQLException { private void testInputProcedure2(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setString(1, charValues[1]); callableStatement.setUniqueIdentifier(2, charValues[6]); @@ -747,26 +734,21 @@ private void testInputProcedure2(String sql) throws SQLException { callableStatement.setString(7, charValues[7]); callableStatement.setNString(8, charValues[8]); - SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery(); - rs.next(); - - assertEquals(rs.getString(1).trim(), charValues[1], "Test for input parameter fails.\n"); - assertEquals(rs.getUniqueIdentifier(2), charValues[6].toUpperCase(), "Test for input parameter fails.\n"); - assertEquals(rs.getString(3).trim(), charValues[2], "Test for input parameter fails.\n"); - assertEquals(rs.getString(4).trim(), charValues[3], "Test for input parameter fails.\n"); - assertEquals(rs.getString(5).trim(), charValues[4], "Test for input parameter fails.\n"); - assertEquals(rs.getString(6).trim(), charValues[5], "Test for input parameter fails.\n"); - assertEquals(rs.getString(7).trim(), charValues[7], "Test for input parameter fails.\n"); - assertEquals(rs.getString(8).trim(), charValues[8], "Test for input parameter fails.\n"); + try (SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery()) { + rs.next(); + assertEquals(rs.getString(1).trim(), charValues[1], "Test for input parameter fails.\n"); + assertEquals(rs.getUniqueIdentifier(2), charValues[6].toUpperCase(), "Test for input parameter fails.\n"); + assertEquals(rs.getString(3).trim(), charValues[2], "Test for input parameter fails.\n"); + assertEquals(rs.getString(4).trim(), charValues[3], "Test for input parameter fails.\n"); + assertEquals(rs.getString(5).trim(), charValues[4], "Test for input parameter fails.\n"); + assertEquals(rs.getString(6).trim(), charValues[5], "Test for input parameter fails.\n"); + assertEquals(rs.getString(7).trim(), charValues[7], "Test for input parameter fails.\n"); + assertEquals(rs.getString(8).trim(), charValues[8], "Test for input parameter fails.\n"); + } } catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure3() throws SQLException { @@ -782,8 +764,7 @@ private void createOutputProcedure3() throws SQLException { private void testOutputProcedure3RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -808,17 +789,11 @@ private void testOutputProcedure3RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure3Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -834,17 +809,11 @@ private void testOutputProcedure3Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -860,11 +829,6 @@ private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure2() throws SQLException { @@ -885,8 +849,7 @@ private void createOutputProcedure2() throws SQLException { private void testOutputProcedure2RandomOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -934,18 +897,12 @@ private void testOutputProcedure2RandomOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure2Inorder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -993,18 +950,12 @@ private void testOutputProcedure2Inorder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure2ReverseOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -1053,11 +1004,6 @@ private void testOutputProcedure2ReverseOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure() throws SQLException { @@ -1076,8 +1022,7 @@ private void createOutputProcedure() throws SQLException { private void testOutputProcedureRandomOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1121,18 +1066,12 @@ private void testOutputProcedureRandomOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureInorder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1169,18 +1108,12 @@ private void testOutputProcedureInorder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureReverseOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1216,11 +1149,6 @@ private void testOutputProcedureReverseOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createInOutProcedure() throws SQLException { @@ -1236,8 +1164,7 @@ private void createInOutProcedure() throws SQLException { private void testInOutProcedure(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(numericValues[3])); callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1250,11 +1177,6 @@ private void testInOutProcedure(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure() throws SQLException { @@ -1271,8 +1193,7 @@ private void createMixedProcedure() throws SQLException { private void testMixedProcedure(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.setInt(2, Integer.parseInt(numericValues[3])); @@ -1296,11 +1217,6 @@ private void testMixedProcedure(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure2() throws SQLException { @@ -1317,8 +1233,7 @@ private void createMixedProcedure2() throws SQLException { private void testMixedProcedure2RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1348,17 +1263,11 @@ private void testMixedProcedure2RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure2Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1375,11 +1284,6 @@ private void testMixedProcedure2Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure3() throws SQLException { @@ -1395,8 +1299,7 @@ private void createMixedProcedure3() throws SQLException { private void testMixedProcedure3RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1426,17 +1329,11 @@ private void testMixedProcedure3RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure3Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1453,17 +1350,11 @@ private void testMixedProcedure3Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1480,11 +1371,6 @@ private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedureNumericPrcisionScale() throws SQLException { @@ -1503,8 +1389,7 @@ private void createMixedProcedureNumericPrcisionScale() throws SQLException { private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQLException { - try { - SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter(2, java.sql.Types.DECIMAL, 10, 5); @@ -1530,17 +1415,11 @@ private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQ catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) throws SQLException { - try { - SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter("p1", java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter("p2", java.sql.Types.DECIMAL, 10, 5); @@ -1566,11 +1445,6 @@ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) thr catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureChar() throws SQLException { @@ -1589,7 +1463,7 @@ private void createOutputProcedureChar() throws SQLException { private void testOutputProcedureCharInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1632,16 +1506,11 @@ private void testOutputProcedureCharInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureCharInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1687,11 +1556,6 @@ private void testOutputProcedureCharInorderObject(String sql) throws SQLExceptio catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureNumeric() throws SQLException { @@ -1788,11 +1652,6 @@ private void testOutputProcedureNumericInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLException { @@ -2009,11 +1868,6 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private Object createValue(Class coercion, @@ -2037,7 +1891,6 @@ private Object createValue(Class coercion, return new BigDecimal(numericValues[index]); } catch (java.lang.NumberFormatException e) { - return null; } return null; } @@ -2156,11 +2009,6 @@ private void testOutputProcedureBinaryInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureBinaryInorderObject(String sql) throws SQLException { @@ -2199,11 +2047,6 @@ private void testOutputProcedureBinaryInorderObject(String sql) throws SQLExcept catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureBinaryInorderString(String sql) throws SQLException { @@ -2217,37 +2060,30 @@ private void testOutputProcedureBinaryInorderString(String sql) throws SQLExcept callableStatement.execute(); int index = 1; - try { - for (int i = 0; i < byteValues.size(); i++) { - String stringValue1 = ("" + callableStatement.getString(index)).trim(); + for (int i = 0; i < byteValues.size(); i++) { + String stringValue1 = ("" + callableStatement.getString(index)).trim(); - StringBuffer expected = new StringBuffer(); - String expectedStr = null; + StringBuffer expected = new StringBuffer(); + String expectedStr = null; - if (null != byteValues.get(i)) { - for (byte b : byteValues.get(i)) { - expected.append(String.format("%02X", b)); - } - expectedStr = "" + expected.toString(); - } - else { - expectedStr = "null"; - } - try { - assertEquals(stringValue1.startsWith(expectedStr), true, - "\nDecryption failed with getString(): " + stringValue1 + ".\nExpected Value: " + expectedStr); - } - catch (Exception e) { - fail(e.toString()); - } - finally { - index++; + if (null != byteValues.get(i)) { + for (byte b : byteValues.get(i)) { + expected.append(String.format("%02X", b)); } + expectedStr = "" + expected.toString(); } - } - finally { - if (null != callableStatement) { - callableStatement.close(); + else { + expectedStr = "null"; + } + try { + assertEquals(stringValue1.startsWith(expectedStr), true, + "\nDecryption failed with getString(): " + stringValue1 + ".\nExpected Value: " + expectedStr); + } + catch (Exception e) { + fail(e.toString()); + } + finally { + index++; } } } @@ -2419,7 +2255,7 @@ private void createOutputProcedureDate() throws SQLException { private void testOutputProcedureDateInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2459,16 +2295,11 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureDateInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2508,11 +2339,6 @@ private void testOutputProcedureDateInorderObject(String sql) throws SQLExceptio catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureBatch() throws SQLException { @@ -2531,8 +2357,7 @@ private void createOutputProcedureBatch() throws SQLException { private void testOutputProcedureBatchInorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -2555,11 +2380,6 @@ private void testOutputProcedureBatchInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure4() throws SQLException { @@ -2614,11 +2434,6 @@ private void testMixedProcedureDateScaleInorder(String sql) throws SQLException catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQLException { @@ -2645,10 +2460,5 @@ private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQL catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java index 0c1de2266..06e44276b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java @@ -512,68 +512,46 @@ public void testNumericNormalization() throws SQLException { private void testChar(SQLServerStatement stmt, String[] values) throws SQLException { String sql = "select * from " + charTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetString(rs, numberOfColumns, values); + testGetObject(rs, numberOfColumns, values); + } + } } - else { - rs = stmt.executeQuery(sql); - } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, values); - testGetObject(rs, numberOfColumns, values); - } - - Util.close(rs, pstmt, null); } private void testBinary(SQLServerStatement stmt, LinkedList values) throws SQLException { String sql = "select * from " + binaryTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); - } - else { - rs = stmt.executeQuery(sql); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetStringForBinary(rs, numberOfColumns, values); + testGetBytes(rs, numberOfColumns, values); + testGetObjectForBinary(rs, numberOfColumns, values); + } + } } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetStringForBinary(rs, numberOfColumns, values); - testGetBytes(rs, numberOfColumns, values); - testGetObjectForBinary(rs, numberOfColumns, values); - } - - Util.close(rs, pstmt, null); } private void testDate(SQLServerStatement stmt, LinkedList values1) throws SQLException { - String sql = "select * from " + dateTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + // testGetStringForDate(rs, numberOfColumns, values1); //TODO: Disabling, since getString throws verification error for zero temporal + // types + testGetObjectForTemporal(rs, numberOfColumns, values1); + testGetDate(rs, numberOfColumns, values1); + } + } } - else { - rs = stmt.executeQuery(sql); - } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - // testGetStringForDate(rs, numberOfColumns, values1); //TODO: Disabling, since getString throws verification error for zero temporal - // types - testGetObjectForTemporal(rs, numberOfColumns, values1); - testGetDate(rs, numberOfColumns, values1); - } - - Util.close(rs, pstmt, null); } private void testGetObject(ResultSet rs, @@ -948,29 +926,22 @@ private void testNumeric(Statement stmt, String[] numericValues, boolean isNull) throws SQLException { String sql = "select * from " + numericTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - SQLServerResultSet rs = null; - if (stmt == null) { - rs = (SQLServerResultSet) pstmt.executeQuery(); - } - else { - rs = (SQLServerResultSet) stmt.executeQuery(sql); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(SQLServerResultSet rs = (stmt == null) ? (SQLServerResultSet) pstmt.executeQuery() : (SQLServerResultSet) stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetString(rs, numberOfColumns, numericValues); + testGetObject(rs, numberOfColumns, numericValues); + testGetBigDecimal(rs, numberOfColumns, numericValues); + if (!isNull) + testWithSpecifiedtype(rs, numberOfColumns, numericValues); + else { + String[] nullNumericValues = {"false", "0", "0", "0", "0", "0.0", "0.0", "0.0", null, null, null, null, null, null, null, null}; + testWithSpecifiedtype(rs, numberOfColumns, nullNumericValues); + } + } + } } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, numericValues); - testGetObject(rs, numberOfColumns, numericValues); - testGetBigDecimal(rs, numberOfColumns, numericValues); - if (!isNull) - testWithSpecifiedtype(rs, numberOfColumns, numericValues); - else { - String[] nullNumericValues = {"false", "0", "0", "0", "0", "0.0", "0.0", "0.0", null, null, null, null, null, null, null, null}; - testWithSpecifiedtype(rs, numberOfColumns, nullNumericValues); - } - } - - Util.close(rs, pstmt, null); } private void testWithSpecifiedtype(SQLServerResultSet rs, diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java index 23dede74d..4d7b8b3d0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -155,38 +155,32 @@ public void testDateScale5Null() throws Exception { private void testNumeric(String[] numeric) throws SQLException { - ResultSet rs = stmt.executeQuery("select * from " + numericTable); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - ArrayList skipMax = new ArrayList<>(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, skipMax, numeric); - testGetBigDecimal(rs, numberOfColumns, numeric); - testGetObject(rs, numberOfColumns, skipMax, numeric); - } - - if (null != rs) { - rs.close(); + try(ResultSet rs = stmt.executeQuery("select * from " + numericTable)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + ArrayList skipMax = new ArrayList<>(); + + while (rs.next()) { + testGetString(rs, numberOfColumns, skipMax, numeric); + testGetBigDecimal(rs, numberOfColumns, numeric); + testGetObject(rs, numberOfColumns, skipMax, numeric); + } } } private void testDate(String[] dateNormalCase, String[] dateSetObject) throws Exception { - ResultSet rs = stmt.executeQuery("select * from " + dateTable); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - ArrayList skipMax = new ArrayList<>(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, skipMax, dateNormalCase); - testGetObject(rs, numberOfColumns, skipMax, dateSetObject); - testGetDate(rs, numberOfColumns, dateSetObject); - } - - if (null != rs) { - rs.close(); + try(ResultSet rs = stmt.executeQuery("select * from " + dateTable)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + ArrayList skipMax = new ArrayList<>(); + + while (rs.next()) { + testGetString(rs, numberOfColumns, skipMax, dateNormalCase); + testGetObject(rs, numberOfColumns, skipMax, dateSetObject); + testGetDate(rs, numberOfColumns, dateSetObject); + } } } @@ -351,79 +345,79 @@ private void testGetDate(ResultSet rs, private void populateDateNormalCase(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, new Timestamp(date.getTime()), scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, new Timestamp(date.getTime())); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1)); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, new Time(date.getTime())); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setTime(i, new Time(date.getTime()), scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, new Timestamp(date.getTime()), scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, new Timestamp(date.getTime())); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1)); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, new Time(date.getTime())); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setTime(i, new Time(date.getTime()), scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), scale); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateNormalCaseNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, null, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, null); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, null); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, null); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setTime(i, null, scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, null, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, null); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, null); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, null); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setTime(i, null, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setDateTimeOffset(i, null, scale); + } + + pstmt.execute(); } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setDateTimeOffset(i, null, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericNormalCase(String[] numeric, @@ -431,25 +425,25 @@ private void populateNumericNormalCase(String[] numeric, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setDouble(i, Double.valueOf(numeric[0])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setDouble(i, Double.valueOf(numeric[0])); + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numeric[1]), precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numeric[2]), precision, scale); + } + + pstmt.execute(); } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numeric[1]), precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numeric[2]), precision, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericSetObject(String[] numeric, @@ -457,129 +451,129 @@ private void populateNumericSetObject(String[] numeric, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, Double.valueOf(numeric[0])); - - } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, new BigDecimal(numeric[1]), java.sql.Types.DECIMAL, precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, new BigDecimal(numeric[2]), java.sql.Types.NUMERIC, precision, scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, Double.valueOf(numeric[0])); + + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, new BigDecimal(numeric[1]), java.sql.Types.DECIMAL, precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, new BigDecimal(numeric[2]), java.sql.Types.NUMERIC, precision, scale); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericSetObjectNull(int precision, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); - + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, precision, scale); + } + + pstmt.execute(); } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, precision, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateSetObject(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET, scale); + } + + pstmt.execute(); } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME, scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateSetObjectNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET, scale); + } + + pstmt.execute(); } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME, scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java index d97726b27..7782a86b7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java @@ -27,9 +27,7 @@ @RunWith(JUnitPlatform.class) public class BulkCopyAllTypes extends AbstractTest { - private static Connection conn = null; - static Statement stmt = null; - + private static DBTable tableSrc = null; private static DBTable tableDest = null; @@ -53,55 +51,43 @@ private void testBulkCopyResultSet(boolean setSelectMethod, Integer resultSetConcurrency) throws SQLException { setupVariation(); - Connection connnection = null; - if (setSelectMethod) { - connnection = DriverManager.getConnection(connectionString + ";selectMethod=cursor;"); - } - else { - connnection = DriverManager.getConnection(connectionString); - } - - Statement stmtement = null; - if (null != resultSetType || null != resultSetConcurrency) { - stmtement = connnection.createStatement(resultSetType, resultSetConcurrency); + try(Connection connnection = DriverManager.getConnection(connectionString + (setSelectMethod ? ";selectMethod=cursor;" : "")); + Statement statement = (null != resultSetType || null != resultSetConcurrency) ? + connnection.createStatement(resultSetType, resultSetConcurrency) : connnection.createStatement()){ + + ResultSet rs = statement.executeQuery("select * from " + tableSrc.getEscapedTableName()); + + SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); + bcOperation.setDestinationTableName(tableDest.getEscapedTableName()); + bcOperation.writeToServer(rs); + bcOperation.close(); + + ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, tableDest); } - else { - stmtement = connnection.createStatement(); - } - - ResultSet rs = stmtement.executeQuery("select * from " + tableSrc.getEscapedTableName()); - - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); - bcOperation.setDestinationTableName(tableDest.getEscapedTableName()); - bcOperation.writeToServer(rs); - bcOperation.close(); - - ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, tableDest); terminateVariation(); } private void setupVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - - DBConnection dbConnection = new DBConnection(connectionString); - DBStatement dbStmt = dbConnection.createStatement(); - - tableSrc = new DBTable(true); - tableDest = tableSrc.cloneSchema(); - - dbStmt.createTable(tableSrc); - dbStmt.createTable(tableDest); - - dbStmt.populateTable(tableSrc); + try(DBConnection dbConnection = new DBConnection(connectionString); + DBStatement dbStmt = dbConnection.createStatement()) { + + tableSrc = new DBTable(true); + tableDest = tableSrc.cloneSchema(); + + dbStmt.createTable(tableSrc); + dbStmt.createTable(tableDest); + + dbStmt.populateTable(tableSrc); + } } private void terminateVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); + try(Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { - Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); - Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); + Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + } } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java index c915ad594..ebf311225 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java @@ -77,9 +77,7 @@ static void setUpConnection() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord") void testCSV() { - SQLServerBulkCSVFileRecord fileRecord; - try { - fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, encoding, delimiter, true); + try (SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, encoding, delimiter, true)) { testBulkCopyCSV(fileRecord, true); } catch (SQLServerException e) { @@ -93,9 +91,7 @@ void testCSV() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord First line not being column name") void testCSVFirstLineNotColumnName() { - SQLServerBulkCSVFileRecord fileRecord; - try { - fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFileNoColumnName, encoding, delimiter, false); + try (SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFileNoColumnName, encoding, delimiter, false)) { testBulkCopyCSV(fileRecord, false); } catch (SQLServerException e) { @@ -111,10 +107,9 @@ void testCSVFirstLineNotColumnName() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord with passing file from url") void testCSVFromURL() throws SQLException { - try { - InputStream csvFileInputStream = new URL( + try (InputStream csvFileInputStream = new URL( "https://raw.githubusercontent.com/Microsoft/mssql-jdbc/master/src/test/resources/BulkCopyCSVTestInput.csv").openStream(); - SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(csvFileInputStream, encoding, delimiter, true); + SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(csvFileInputStream, encoding, delimiter, true)) { testBulkCopyCSV(fileRecord, true); } catch (Exception e) { @@ -125,53 +120,52 @@ void testCSVFromURL() throws SQLException { private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, boolean firstLineIsColumnNames) { DBTable destTable = null; - try { - BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding)); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { // read the first line from csv and parse it to get datatypes to create destination column String[] columnTypes = br.readLine().substring(1)/* Skip the Byte order mark */.split(delimiter, -1); br.close(); int numberOfColumns = columnTypes.length; destTable = new DBTable(false); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - bulkCopy.setDestinationTableName(destTable.getEscapedTableName()); - - // add a column in destTable for each datatype in csv - for (int i = 0; i < numberOfColumns; i++) { - SqlType sqlType = null; - int precision = -1; - int scale = -1; - - String columnType = columnTypes[i].trim().toLowerCase(); - int indexOpenParenthesis = columnType.lastIndexOf("("); - // skip the parenthesis in case of precision and scale type - if (-1 != indexOpenParenthesis) { - String precision_scale = columnType.substring(indexOpenParenthesis + 1, columnType.length() - 1); - columnType = columnType.substring(0, indexOpenParenthesis); - sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; - - // add scale if exist - int indexPrecisionScaleSeparator = precision_scale.indexOf("-"); - if (-1 != indexPrecisionScaleSeparator) { - scale = Integer.parseInt(precision_scale.substring(indexPrecisionScaleSeparator + 1)); - sqlType.setScale(scale); - precision_scale = precision_scale.substring(0, indexPrecisionScaleSeparator); - } - // add precision - precision = Integer.parseInt(precision_scale); - sqlType.setPrecision(precision); - } - else { - sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; - } - - destTable.addColumn(sqlType); - fileRecord.addColumnMetadata(i + 1, "", sqlType.getJdbctype().getVendorTypeNumber(), (-1 == precision) ? 0 : precision, - (-1 == scale) ? 0 : scale); + try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy((Connection) con.product())) { + bulkCopy.setDestinationTableName(destTable.getEscapedTableName()); + + // add a column in destTable for each datatype in csv + for (int i = 0; i < numberOfColumns; i++) { + SqlType sqlType = null; + int precision = -1; + int scale = -1; + + String columnType = columnTypes[i].trim().toLowerCase(); + int indexOpenParenthesis = columnType.lastIndexOf("("); + // skip the parenthesis in case of precision and scale type + if (-1 != indexOpenParenthesis) { + String precision_scale = columnType.substring(indexOpenParenthesis + 1, columnType.length() - 1); + columnType = columnType.substring(0, indexOpenParenthesis); + sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; + + // add scale if exist + int indexPrecisionScaleSeparator = precision_scale.indexOf("-"); + if (-1 != indexPrecisionScaleSeparator) { + scale = Integer.parseInt(precision_scale.substring(indexPrecisionScaleSeparator + 1)); + sqlType.setScale(scale); + precision_scale = precision_scale.substring(0, indexPrecisionScaleSeparator); + } + // add precision + precision = Integer.parseInt(precision_scale); + sqlType.setPrecision(precision); + } + else { + sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; + } + + destTable.addColumn(sqlType); + fileRecord.addColumnMetadata(i + 1, "", sqlType.getJdbctype().getVendorTypeNumber(), (-1 == precision) ? 0 : precision, + (-1 == scale) ? 0 : scale); + } + stmt.createTable(destTable); + bulkCopy.writeToServer((ISQLServerBulkRecord) fileRecord); } - stmt.createTable(destTable); - bulkCopy.writeToServer((ISQLServerBulkRecord) fileRecord); - bulkCopy.close(); if (firstLineIsColumnNames) validateValuesFromCSV(destTable, inputFile); else @@ -186,7 +180,6 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, stmt.dropTable(destTable); } } - } /** @@ -196,30 +189,28 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, */ static void validateValuesFromCSV(DBTable destinationTable, String inputFile) { - BufferedReader br; - try { - br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding)); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { if (inputFile.equalsIgnoreCase("BulkCopyCSVTestInput.csv")) br.readLine(); // skip first line as it is header - DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - while (dstResultSet.next()) { - String[] srcValues = br.readLine().split(delimiter); - if ((0 == srcValues.length) && (srcValues.length != totalColumns)) { - srcValues = new String[totalColumns]; - Arrays.fill(srcValues, null); - } - for (int i = 1; i <= totalColumns; i++) { - String srcValue = srcValues[i - 1]; - String dstValue = dstResultSet.getString(i); - srcValue = (null != srcValue) ? srcValue.trim() : srcValue; - dstValue = (null != dstValue) ? dstValue.trim() : dstValue; - - // get the value from csv as string and compare them - ComparisonUtil.compareExpectedAndActual(java.sql.Types.VARCHAR, srcValue, dstValue); - } + try (DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + while (dstResultSet.next()) { + String[] srcValues = br.readLine().split(delimiter); + if ((0 == srcValues.length) && (srcValues.length != totalColumns)) { + srcValues = new String[totalColumns]; + Arrays.fill(srcValues, null); + } + for (int i = 1; i <= totalColumns; i++) { + String srcValue = srcValues[i - 1]; + String dstValue = dstResultSet.getString(i); + srcValue = (null != srcValue) ? srcValue.trim() : srcValue; + dstValue = (null != dstValue) ? dstValue.trim() : dstValue; + // get the value from csv as string and compare them + ComparisonUtil.compareExpectedAndActual(java.sql.Types.VARCHAR, srcValue, dstValue); + } + } } } catch (Exception e) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java index 22570060a..2de49b360 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -332,31 +332,32 @@ void testInvalidCM() { private void validateValuesRepetativeCM(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { - DBStatement srcStmt = con.createStatement(); - DBStatement dstStmt = con.createStatement(); - DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData sourceMeta = ((ResultSet) srcResultSet.product()).getMetaData(); - int totalColumns = sourceMeta.getColumnCount(); - - // verify data from sourceType and resultSet - while (srcResultSet.next() && dstResultSet.next()) - for (int i = 1; i <= totalColumns; i++) { - // TODO: check row and column count in both the tables - - Object srcValue, dstValue; - srcValue = srcResultSet.getObject(i); - dstValue = dstResultSet.getObject(i); - ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValue, dstValue); - - // compare value of first column of source with extra column in destination - if (1 == i) { - Object srcValueFirstCol = srcResultSet.getObject(i); - Object dstValLastCol = dstResultSet.getObject(totalColumns + 1); - ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValueFirstCol, dstValLastCol); - } - } - + try(DBStatement srcStmt = con.createStatement(); + DBStatement dstStmt = con.createStatement(); + DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData sourceMeta = ((ResultSet) srcResultSet.product()).getMetaData(); + int totalColumns = sourceMeta.getColumnCount(); + + // verify data from sourceType and resultSet + while (srcResultSet.next() && dstResultSet.next()) { + for (int i = 1; i <= totalColumns; i++) { + // TODO: check row and column count in both the tables + + Object srcValue, dstValue; + srcValue = srcResultSet.getObject(i); + dstValue = dstResultSet.getObject(i); + ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValue, dstValue); + + // compare value of first column of source with extra column in destination + if (1 == i) { + Object srcValueFirstCol = srcResultSet.getObject(i); + Object dstValLastCol = dstResultSet.getObject(totalColumns + 1); + ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValueFirstCol, dstValLastCol); + } + } + } + } } private void dropTable(String tableName) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java index 340dbb3eb..f56039813 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java @@ -12,6 +12,7 @@ import java.lang.reflect.Method; import java.sql.Connection; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; @@ -88,9 +89,11 @@ public void execute() { void testInvalidConnection1() { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override - public void execute() throws SQLServerException { - Connection con = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + public void execute() throws SQLException { + try(Connection con = null; + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con)) { + //do nothing + } } }); } @@ -104,8 +107,10 @@ void testInvalidConnection2() { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override public void execute() throws SQLServerException { - SQLServerConnection con = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + try(SQLServerConnection con = null; + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con)) { + //do nothing + } } }); } @@ -120,7 +125,9 @@ void testInvalidConnection3() { @Override public void execute() throws SQLServerException { String connectionUrl = " "; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl); + try(SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl)) { + //do nothing + } } }); } @@ -135,7 +142,9 @@ void testInvalidConnection4() { @Override public void execute() throws SQLServerException { String connectionUrl = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl); + try(SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl)) { + //do nothing + } } }); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java index 60e7e3da4..1be4ad850 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java @@ -38,39 +38,18 @@ @DisplayName("Test ISQLServerBulkRecord") public class BulkCopyISQLServerBulkRecordTest extends AbstractTest { - static DBConnection con = null; - static DBStatement stmt = null; - static DBTable dstTable = null; - - /** - * Create connection and statement - */ - @BeforeAll - static void setUpConnection() { - con = new DBConnection(connectionString); - stmt = con.createStatement(); - } - @Test - void testISQLServerBulkRecord() { - dstTable = new DBTable(true); - stmt.createTable(dstTable); - BulkData Bdata = new BulkData(); - - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, Bdata, dstTable); - } - - /** - * drop source table after testing bulk copy - * - * @throws SQLException - */ - @AfterAll - static void tearConnection() throws SQLException { - stmt.close(); - con.close(); + void testISQLServerBulkRecord() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement()) { + DBTable dstTable = new DBTable(true); + stmt.createTable(dstTable); + BulkData Bdata = new BulkData(dstTable); + + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, Bdata, dstTable); + } } class BulkData implements ISQLServerBulkRecord { @@ -98,7 +77,7 @@ private class ColumnMetadata { Map columnMetadata; List data; - BulkData() { + BulkData(DBTable dstTable) { columnMetadata = new HashMap<>(); totalColumn = dstTable.totalColumns(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java index eeaad7577..774deff4a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -20,7 +20,6 @@ import java.util.Properties; import java.util.TimeZone; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -33,9 +32,6 @@ @RunWith(JUnitPlatform.class) public class BulkCopyResultSetCursorTest extends AbstractTest { - private static Connection conn = null; - static Statement stmt = null; - static BigDecimal[] expectedBigDecimals = {new BigDecimal("12345.12345"), new BigDecimal("125.123"), new BigDecimal("45.12345")}; static String[] expectedBigDecimalStrings = {"12345.12345", "125.12300", "45.12345"}; @@ -62,27 +58,20 @@ public void testServerCursors() throws SQLException { private void serverCursorsTest(int resultSetType, int resultSetConcurrency) throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - - verifyDestinationTableData(expectedBigDecimals.length); - - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != rs) { - rs.close(); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency).executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -95,28 +84,19 @@ private void serverCursorsTest(int resultSetType, public void testSelectMethodSetToCursor() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - conn = DriverManager.getConnection(connectionString, info); - - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - - verifyDestinationTableData(expectedBigDecimals.length); - - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != rs) { - rs.close(); + try (Connection conn = DriverManager.getConnection(connectionString, info); + Statement stmt = conn.createStatement()) { + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -127,133 +107,106 @@ public void testSelectMethodSetToCursor() throws SQLException { */ @Test public void testMultiplePreparedStatementAndResultSet() throws SQLException { - conn = DriverManager.getConnection(connectionString); - - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length); - - rs.beforeFirst(); - SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn); - bulkCopy1.setDestinationTableName(desTable); - bulkCopy1.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length * 2); - - rs.beforeFirst(); - SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn); - bulkCopy2.setDestinationTableName(desTable); - bulkCopy2.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length * 3); - - String sql = "insert into " + desTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql); - for (int i = 0; i < expectedBigDecimals.length; i++) { - pstmt1.setBigDecimal(1, expectedBigDecimals[i]); - pstmt1.setString(2, expectedStrings[i]); - pstmt1.setTimestamp(3, expectedTimestamps[i], calGMT); - pstmt1.setString(4, expectedStrings[i]); - pstmt1.execute(); - } - verifyDestinationTableData(expectedBigDecimals.length * 4); - - ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn); - bulkCopy3.setDestinationTableName(desTable); - bulkCopy3.writeToServer(rs2); - verifyDestinationTableData(expectedBigDecimals.length * 5); - - if (null != pstmt1) { - pstmt1.close(); - } - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != bulkCopy1) { - bulkCopy1.close(); - } - if (null != bulkCopy2) { - bulkCopy2.close(); - } - if (null != bulkCopy3) { - bulkCopy3.close(); - } - if (null != rs) { - rs.close(); - } - if (null != rs2) { - rs2.close(); - } + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable)) { + try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length); + } + + rs.beforeFirst(); + try (SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn)) { + bulkCopy1.setDestinationTableName(desTable); + bulkCopy1.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length * 2); + } + + rs.beforeFirst(); + try (SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn)) { + bulkCopy2.setDestinationTableName(desTable); + bulkCopy2.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length * 3); + } + + String sql = "insert into " + desTable + " values (?,?,?,?)"; + Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + try (SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { + for (int i = 0; i < expectedBigDecimals.length; i++) { + pstmt1.setBigDecimal(1, expectedBigDecimals[i]); + pstmt1.setString(2, expectedStrings[i]); + pstmt1.setTimestamp(3, expectedTimestamps[i], calGMT); + pstmt1.setString(4, expectedStrings[i]); + pstmt1.execute(); + } + verifyDestinationTableData(expectedBigDecimals.length * 4); + } + try (ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn)) { + bulkCopy3.setDestinationTableName(desTable); + bulkCopy3.writeToServer(rs2); + verifyDestinationTableData(expectedBigDecimals.length * 5); + } + } + } } private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { - ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable); - - int expectedArrayLength = expectedBigDecimals.length; - - int i = 0; - while (rs.next()) { - assertTrue(rs.getString(1).equals(expectedBigDecimalStrings[i % expectedArrayLength]), - "Expected Value:" + expectedBigDecimalStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(1)); - assertTrue(rs.getString(2).trim().equals(expectedStrings[i % expectedArrayLength]), - "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(2)); - assertTrue(rs.getString(3).equals(expectedTimestampStrings[i % expectedArrayLength]), - "Expected Value:" + expectedTimestampStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(3)); - assertTrue(rs.getString(4).trim().equals(expectedStrings[i % expectedArrayLength]), - "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(4)); - i++; + try (Connection conn = DriverManager.getConnection(connectionString); + ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + + int expectedArrayLength = expectedBigDecimals.length; + + int i = 0; + while (rs.next()) { + assertTrue(rs.getString(1).equals(expectedBigDecimalStrings[i % expectedArrayLength]), + "Expected Value:" + expectedBigDecimalStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(1)); + assertTrue(rs.getString(2).trim().equals(expectedStrings[i % expectedArrayLength]), + "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(2)); + assertTrue(rs.getString(3).equals(expectedTimestampStrings[i % expectedArrayLength]), + "Expected Value:" + expectedTimestampStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(3)); + assertTrue(rs.getString(4).trim().equals(expectedStrings[i % expectedArrayLength]), + "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(4)); + i++; + } + + assertTrue(i == expectedNumberOfRows); } - - assertTrue(i == expectedNumberOfRows); } private static void populateSourceTable() throws SQLException { String sql = "insert into " + srcTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql); + try (Connection conn = DriverManager.getConnection(connectionString); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { - for (int i = 0; i < expectedBigDecimals.length; i++) { - pstmt.setBigDecimal(1, expectedBigDecimals[i]); - pstmt.setString(2, expectedStrings[i]); - pstmt.setTimestamp(3, expectedTimestamps[i], calGMT); - pstmt.setString(4, expectedStrings[i]); - pstmt.execute(); + for (int i = 0; i < expectedBigDecimals.length; i++) { + pstmt.setBigDecimal(1, expectedBigDecimals[i]); + pstmt.setString(2, expectedStrings[i]); + pstmt.setTimestamp(3, expectedTimestamps[i], calGMT); + pstmt.setString(4, expectedStrings[i]); + pstmt.execute(); + } } } - private static void dropTables() throws SQLException { + private static void dropTables(Statement stmt) throws SQLException { Utils.dropTableIfExists(srcTable, stmt); Utils.dropTableIfExists(desTable, stmt); } - private static void createTables() throws SQLException { + private static void createTables(Statement stmt) throws SQLException { String sql = "create table " + srcTable + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); sql = "create table " + desTable + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } - - @AfterEach - private void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java index 2b23bf836..f916336de 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java @@ -7,6 +7,8 @@ */ package com.microsoft.sqlserver.jdbc.bulkCopy; +import java.sql.SQLException; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.platform.runner.JUnitPlatform; @@ -28,39 +30,28 @@ public class BulkCopyTestSetUp extends AbstractTest { /** * Create source table needed for testing bulk copy + * @throws SQLException */ @BeforeAll - static void setUpSourceTable() { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(connectionString); - stmt = con.createStatement(); + static void setUpSourceTable() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement(); + DBPreparedStatement pstmt = new DBPreparedStatement(con);) { sourceTable = new DBTable(true); stmt.createTable(sourceTable); - DBPreparedStatement pstmt = new DBPreparedStatement(con); pstmt.populateTable(sourceTable); } - finally { - con.close(); - } } /** * drop source table after testing bulk copy + * @throws SQLException */ @AfterAll - static void dropSourceTable() { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(connectionString); - stmt = con.createStatement(); + static void dropSourceTable() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement()) { stmt.dropTable(sourceTable); } - finally { - con.close(); - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java index fd51ef544..0b902587e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java @@ -7,20 +7,12 @@ */ package com.microsoft.sqlserver.jdbc.bulkCopy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.math.BigDecimal; import java.sql.Connection; -import java.sql.Date; -import java.sql.JDBCType; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; -import java.sql.Time; -import java.sql.Timestamp; - import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.bulkCopy.BulkCopyTestWrapper.ColumnMap; @@ -28,7 +20,6 @@ import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.ComparisonUtil; /** @@ -70,57 +61,53 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, boolean validateResult) { - DBConnection con = null; - DBStatement stmt = null; DBTable destinationTable = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement()) { destinationTable = sourceTable.cloneSchema(); stmt.createTable(destinationTable); - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); + try (DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } + catch (SQLException ex) { + fail(ex.getMessage()); } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); + finally { + stmt.dropTable(destinationTable); + con.close(); } } catch (SQLException ex) { fail(ex.getMessage()); } - finally { - stmt.dropTable(destinationTable); - con.close(); - } } /** @@ -135,20 +122,12 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, DBTable destinationTable, boolean validateResult) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { if (wrapper.isUsingBulkCopyOptions()) { bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); } @@ -171,18 +150,13 @@ else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { } } bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - bulkCopy.close(); if (validateResult) { validateValues(con, sourceTable, destinationTable); } - } + } catch (SQLException ex) { fail(ex.getMessage()); } - finally { - stmt.dropTable(destinationTable); - con.close(); - } } /** @@ -199,58 +173,54 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable destinationTable, boolean validateResult, boolean fail) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } - } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - if (fail) - fail("bulkCopy.writeToServer did not fail when it should have"); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); - } - } - catch (SQLException ex) { + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + try { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (fail) + fail("bulkCopy.writeToServer did not fail when it should have"); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } + } catch (SQLException ex) { + if (!fail) { + fail(ex.getMessage()); + } + } + finally { + stmt.dropTable(destinationTable); + con.close(); + } + } catch (SQLException e) { if (!fail) { - fail(ex.getMessage()); + fail(e.getMessage()); } - } - finally { - stmt.dropTable(destinationTable); - con.close(); - } + } } /** @@ -269,60 +239,59 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, boolean validateResult, boolean fail, boolean dropDest) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } - } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - if (fail) - fail("bulkCopy.writeToServer did not fail when it should have"); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); - } + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + try { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (fail) + fail("bulkCopy.writeToServer did not fail when it should have"); + bulkCopy.close(); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } + } + catch (SQLException ex) { + if (!fail) { + fail(ex.getMessage()); + } + } + finally { + if (dropDest) { + stmt.dropTable(destinationTable); + } + con.close(); + } } catch (SQLException ex) { if (!fail) { fail(ex.getMessage()); } } - finally { - if (dropDest) { - stmt.dropTable(destinationTable); - } - con.close(); - } } /** @@ -336,24 +305,26 @@ else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { static void validateValues(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { - DBStatement srcStmt = con.createStatement(); - DBStatement dstStmt = con.createStatement(); - DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - - // verify data from sourceType and resultSet - while (srcResultSet.next() && dstResultSet.next()) - for (int i = 1; i <= totalColumns; i++) { - // TODO: check row and column count in both the tables - - Object srcValue, dstValue; - srcValue = srcResultSet.getObject(i); - dstValue = dstResultSet.getObject(i); - - ComparisonUtil.compareExpectedAndActual(destMeta.getColumnType(i), srcValue, dstValue); - } + try (DBStatement srcStmt = con.createStatement(); + DBStatement dstStmt = con.createStatement(); + DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + + // verify data from sourceType and resultSet + while (srcResultSet.next() && dstResultSet.next()) { + for (int i = 1; i <= totalColumns; i++) { + // TODO: check row and column count in both the tables + + Object srcValue, dstValue; + srcValue = srcResultSet.getObject(i); + dstValue = dstResultSet.getObject(i); + + ComparisonUtil.compareExpectedAndActual(destMeta.getColumnType(i), srcValue, dstValue); + } + } + } } /** @@ -365,22 +336,16 @@ static void validateValues(DBConnection con, static void performBulkCopy(BulkCopyTestWrapper bulkWrapper, ISQLServerBulkRecord srcData, DBTable dstTable) { - SQLServerBulkCopy bc; - DBConnection con = new DBConnection(bulkWrapper.getConnectionString()); - DBStatement stmt = con.createStatement(); - try { - bc = new SQLServerBulkCopy(bulkWrapper.getConnectionString()); + try (DBConnection con = new DBConnection(bulkWrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + SQLServerBulkCopy bc = new SQLServerBulkCopy(bulkWrapper.getConnectionString());) { bc.setDestinationTableName(dstTable.getEscapedTableName()); bc.writeToServer(srcData); - bc.close(); validateValues(con, srcData, dstTable); } catch (Exception e) { fail(e.getMessage()); } - finally { - con.close(); - } } /** @@ -395,38 +360,38 @@ static void validateValues( ISQLServerBulkRecord srcData, DBTable destinationTable) throws Exception { - DBStatement dstStmt = con.createStatement(); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - - // reset the counter in ISQLServerBulkRecord, which was incremented during read by BulkCopy - java.lang.reflect.Method method = srcData.getClass().getMethod("reset"); - method.invoke(srcData); - - - // verify data from sourceType and resultSet - while (srcData.next() && dstResultSet.next()) - { - Object[] srcValues = srcData.getRowData(); - for (int i = 1; i <= totalColumns; i++) { - - Object srcValue, dstValue; - srcValue = srcValues[i-1]; - if(srcValue.getClass().getName().equalsIgnoreCase("java.lang.Double")){ - // in case of SQL Server type Float (ie java type double), in float(n) if n is <=24 ie precsion is <=7 SQL Server type Real is returned(ie java type float) - if(destMeta.getPrecision(i) <8) - srcValue = new Float(((Double)srcValue)); - } - dstValue = dstResultSet.getObject(i); - int dstType = destMeta.getColumnType(i); - if(java.sql.Types.TIMESTAMP != dstType - && java.sql.Types.TIME != dstType - && microsoft.sql.Types.DATETIMEOFFSET != dstType){ - // skip validation for temporal types due to rounding eg 7986-10-21 09:51:15.114 is rounded as 7986-10-21 09:51:15.113 in server - ComparisonUtil.compareExpectedAndActual(dstType, srcValue, dstValue); - } - } + try (DBStatement dstStmt = con.createStatement(); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + + // reset the counter in ISQLServerBulkRecord, which was incremented during read by BulkCopy + java.lang.reflect.Method method = srcData.getClass().getMethod("reset"); + method.invoke(srcData); + + // verify data from sourceType and resultSet + while (srcData.next() && dstResultSet.next()) + { + Object[] srcValues = srcData.getRowData(); + for (int i = 1; i <= totalColumns; i++) { + + Object srcValue, dstValue; + srcValue = srcValues[i-1]; + if(srcValue.getClass().getName().equalsIgnoreCase("java.lang.Double")){ + // in case of SQL Server type Float (ie java type double), in float(n) if n is <=24 ie precsion is <=7 SQL Server type Real is returned(ie java type float) + if(destMeta.getPrecision(i) <8) + srcValue = new Float(((Double)srcValue)); + } + dstValue = dstResultSet.getObject(i); + int dstType = destMeta.getColumnType(i); + if(java.sql.Types.TIMESTAMP != dstType + && java.sql.Types.TIME != dstType + && microsoft.sql.Types.DATETIMEOFFSET != dstType){ + // skip validation for temporal types due to rounding eg 7986-10-21 09:51:15.114 is rounded as 7986-10-21 09:51:15.113 in server + ComparisonUtil.compareExpectedAndActual(dstType, srcValue, dstValue); + } + } + } } } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java index a2f5bdaac..3773e75fa 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java @@ -38,13 +38,7 @@ public class BulkCopyTimeoutTest extends BulkCopyTestSetUp { @Test @DisplayName("BulkCopy:test zero timeout") void testZeroTimeOut() throws SQLServerException { - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); - option.setBulkCopyTimeout(0); - bulkWrapper.useBulkCopyOptions(true); - bulkWrapper.setBulkOptions(option); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + testBulkCopyWithTimeout(0); } /** @@ -58,14 +52,18 @@ void testNegativeTimeOut() throws SQLServerException { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override public void execute() throws SQLServerException { - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); - option.setBulkCopyTimeout(-1); - bulkWrapper.useBulkCopyOptions(true); - bulkWrapper.setBulkOptions(option); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + testBulkCopyWithTimeout(-1); } }); } + + private void testBulkCopyWithTimeout(int timeout) throws SQLServerException { + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); + option.setBulkCopyTimeout(timeout); + bulkWrapper.useBulkCopyOptions(true); + bulkWrapper.setBulkOptions(option); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java index 1b45d54a5..bbb83e148 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java @@ -56,13 +56,11 @@ public class ISQLServerBulkRecordIssuesTest extends AbstractTest { @Test public void testVarchar() throws Exception { variation = "testVarchar"; - BulkDat bData = new BulkDat(variation); - String value = "aa"; + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (smallDATA varchar(2))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); bcOperation.close(); @@ -86,19 +84,20 @@ public void testVarchar() throws Exception { @Test public void testSmalldatetime() throws Exception { variation = "testSmalldatetime"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); String value = ("1954-05-22 02:44:00.0").toString(); query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; stmt.executeUpdate(query); - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - bcOperation.close(); - - ResultSet rs = stmt.executeQuery("select * from " + destTable); - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(destTable); + bcOperation.writeToServer(bData); + + try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } + } } } @@ -110,16 +109,14 @@ public void testSmalldatetime() throws Exception { @Test public void testSmalldatetimeOutofRange() throws Exception { variation = "testSmalldatetimeOutofRange"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testSmalldatetimeOutofRange when it it was expected to fail"); } catch (Exception e) { @@ -141,15 +138,13 @@ public void testSmalldatetimeOutofRange() throws Exception { @Test public void testBinaryColumnAsByte() throws Exception { variation = "testBinaryColumnAsByte"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testBinaryColumnAsByte when it it was expected to fail"); } catch (Exception e) { @@ -170,15 +165,13 @@ public void testBinaryColumnAsByte() throws Exception { @Test public void testBinaryColumnAsString() throws Exception { variation = "testBinaryColumnAsString"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testBinaryColumnAsString when it it was expected to fail"); } catch (Exception e) { @@ -199,20 +192,18 @@ public void testBinaryColumnAsString() throws Exception { @Test public void testSendValidValueforBinaryColumnAsString() throws Exception { variation = "testSendValidValueforBinaryColumnAsString"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); - ResultSet rs = stmt.executeQuery("select * from " + destTable); - String value = "0101010000"; - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), "0101010000"); + } } } catch (Exception e) { @@ -258,7 +249,7 @@ public static void afterAllTests() throws SQLException { } -class BulkDat implements ISQLServerBulkRecord { +class BulkData implements ISQLServerBulkRecord { boolean isStringData = false; private class ColumnMetadata { @@ -286,7 +277,7 @@ private class ColumnMetadata { int counter = 0; int rowCount = 1; - BulkDat(String variation) { + BulkData(String variation) { if (variation.equalsIgnoreCase("testVarchar")) { isStringData = true; columnMetadata = new HashMap<>(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java index 8898be8b9..eaad85365 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java @@ -33,10 +33,6 @@ @DisplayName("BVT Test") public class bvtTest extends bvtTestSetup { private static String driverNamePattern = "Microsoft JDBC Driver \\d.\\d for SQL Server"; - private static DBResultSet rs = null; - private static DBPreparedStatement pstmt = null; - private static DBConnection conn = null; - private static DBStatement stmt = null; /** * Connect to specified server and close the connection @@ -46,13 +42,7 @@ public class bvtTest extends bvtTestSetup { @Test @DisplayName("test connection") public void testConnection() throws SQLException { - try { - conn = new DBConnection(connectionString); - conn.close(); - } - finally { - terminateVariation(); - } + try (DBConnection conn = new DBConnection(connectionString)) {} } /** @@ -62,15 +52,11 @@ public void testConnection() throws SQLException { */ @Test public void testConnectionIsClosed() throws SQLException { - try { - conn = new DBConnection(connectionString); + try (DBConnection conn = new DBConnection(connectionString)) { assertTrue(!conn.isClosed(), "BVT connection should not be closed"); conn.close(); assertTrue(conn.isClosed(), "BVT connection should not be open"); } - finally { - terminateVariation(); - } } /** @@ -80,8 +66,7 @@ public void testConnectionIsClosed() throws SQLException { */ @Test public void testDriverNameAndDriverVersion() throws SQLException { - try { - conn = new DBConnection(connectionString); + try (DBConnection conn = new DBConnection(connectionString)) { DatabaseMetaData metaData = conn.getMetaData(); Pattern p = Pattern.compile(driverNamePattern); Matcher m = p.matcher(metaData.getDriverName()); @@ -90,9 +75,6 @@ public void testDriverNameAndDriverVersion() throws SQLException { if (parts.length != 4) assertTrue(true, "Driver version number should be four parts! "); } - finally { - terminateVariation(); - } } /** @@ -103,16 +85,12 @@ public void testDriverNameAndDriverVersion() throws SQLException { @Test public void testCreateStatement() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - String query = "SELECT * FROM " + table1.getEscapedTableName() + ";"; - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName() + ";"; + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { rs.verify(table1); - rs.close(); - } - finally { - terminateVariation(); } } @@ -124,14 +102,10 @@ public void testCreateStatement() throws SQLException { @Test public void testCreateStatementWithQueryTimeout() throws SQLException { - try { - conn = new DBConnection(connectionString + ";querytimeout=10"); - stmt = conn.createStatement(); + try (DBConnection conn = new DBConnection(connectionString + ";querytimeout=10"); + DBStatement stmt = conn.createStatement()) { assertEquals(10, stmt.getQueryTimeout()); } - finally { - terminateVariation(); - } } /** @@ -144,11 +118,11 @@ public void testCreateStatementWithQueryTimeout() throws SQLException { @Test public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY); - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); rs.verifyCurrentRow(table1); @@ -164,9 +138,6 @@ public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundExce } rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -178,11 +149,9 @@ public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundExce */ @Test public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFoundException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY); - - rs = stmt.selectAll(table1); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY); + DBResultSet rs = stmt.selectAll(table1)) { rs.next(); rs.verifyCurrentRow(table1); rs.afterLast(); @@ -190,9 +159,6 @@ public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFou rs.verifyCurrentRow(table1); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -204,12 +170,11 @@ public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFou @Test public void testStmtScrollSensitiveReadOnly() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); rs.next(); rs.verifyCurrentRow(table1); @@ -219,9 +184,6 @@ public void testStmtScrollSensitiveReadOnly() throws SQLException { rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -232,13 +194,12 @@ public void testStmtScrollSensitiveReadOnly() throws SQLException { */ @Test public void testStmtForwardOnlyUpdateable() throws SQLException { + + String query = "SELECT * FROM " + table1.getEscapedTableName(); - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_UPDATABLE); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_UPDATABLE); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); // Verify resultset behavior @@ -255,9 +216,6 @@ public void testStmtForwardOnlyUpdateable() throws SQLException { } rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -269,12 +227,11 @@ public void testStmtForwardOnlyUpdateable() throws SQLException { @Test public void testStmtScrollSensitiveUpdatable() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE); + DBResultSet rs = stmt.executeQuery(query)) { // Verify resultset behavior rs.next(); @@ -285,9 +242,6 @@ public void testStmtScrollSensitiveUpdatable() throws SQLException { rs.absolute(1); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -298,11 +252,9 @@ public void testStmtScrollSensitiveUpdatable() throws SQLException { @Test public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_DYNAMIC_CONCUR_OPTIMISTIC); - - rs = stmt.selectAll(table1); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_DYNAMIC_CONCUR_OPTIMISTIC); + DBResultSet rs = stmt.selectAll(table1)) { // Verify resultset behavior rs.next(); @@ -310,9 +262,6 @@ public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { rs.previous(); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -323,23 +272,16 @@ public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { @Test public void testStmtSserverCursorForwardOnly() throws SQLException { - try { - conn = new DBConnection(connectionString); - DBResultSetTypes rsType = DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY; - stmt = conn.createStatement(rsType.resultsetCursor, rsType.resultSetConcurrency); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - - rs = stmt.executeQuery(query); - + DBResultSetTypes rsType = DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY; + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(rsType.resultsetCursor, rsType.resultSetConcurrency); + DBResultSet rs = stmt.executeQuery(query)) { // Verify resultset behavior rs.next(); rs.verify(table1); } - finally { - terminateVariation(); - } - } /** @@ -350,21 +292,17 @@ public void testStmtSserverCursorForwardOnly() throws SQLException { @Test public void testCreatepreparedStatement() throws SQLException { - try { - conn = new DBConnection(connectionString); - String colName = table1.getColumnName(7); - String value = table1.getRowData(7, 0).toString(); + String colName = table1.getColumnName(7); + String value = table1.getRowData(7, 0).toString(); + String query = "SELECT * from " + table1.getEscapedTableName() + " where [" + colName + "] = ? "; + + try (DBConnection conn = new DBConnection(connectionString); + DBPreparedStatement pstmt = conn.prepareStatement(query)) { - String query = "SELECT * from " + table1.getEscapedTableName() + " where [" + colName + "] = ? "; - - pstmt = conn.prepareStatement(query); pstmt.setObject(1, new BigDecimal(value)); - - rs = pstmt.executeQuery(); + DBResultSet rs = pstmt.executeQuery(); rs.verify(table1); - } - finally { - terminateVariation(); + rs.close(); } } @@ -376,19 +314,14 @@ public void testCreatepreparedStatement() throws SQLException { @Test public void testResultSet() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); - + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { // verify resultSet rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -399,12 +332,11 @@ public void testResultSet() throws SQLException { @Test public void testResultSetAndClose() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { try { if (null != rs) @@ -414,9 +346,6 @@ public void testResultSetAndClose() throws SQLException { fail(e.toString()); } } - finally { - terminateVariation(); - } } /** @@ -426,22 +355,17 @@ public void testResultSetAndClose() throws SQLException { */ @Test public void testTwoResultsetsDifferentStmt() throws SQLException { + + String query = "SELECT * FROM " + table1.getEscapedTableName(); + String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - DBStatement stmt1 = null; - DBStatement stmt2 = null; - DBResultSet rs1 = null; - DBResultSet rs2 = null; - try { - conn = new DBConnection(connectionString); - stmt1 = conn.createStatement(); - stmt2 = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs1 = stmt1.executeQuery(query); - - String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - rs2 = stmt2.executeQuery(query2); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt1 = conn.createStatement(); + DBStatement stmt2 = conn.createStatement()) { + DBResultSet rs1 = stmt1.executeQuery(query); + DBResultSet rs2 = stmt2.executeQuery(query2); + // Interleave resultset calls rs1.next(); rs1.verifyCurrentRow(table1); @@ -453,21 +377,7 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { rs1.close(); rs2.next(); rs2.verify(table2); - } - finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - if (null != stmt1) { - stmt1.close(); - } - if (null != stmt2) { - stmt2.close(); - } - terminateVariation(); + rs2.close(); } } @@ -479,18 +389,14 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { @Test public void testTwoResultsetsSameStmt() throws SQLException { - DBResultSet rs1 = null; - DBResultSet rs2 = null; - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs1 = stmt.executeQuery(query); - - String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - rs2 = stmt.executeQuery(query2); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + String query2 = "SELECT * FROM " + table2.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { + DBResultSet rs1 = stmt.executeQuery(query); + DBResultSet rs2 = stmt.executeQuery(query2); // Interleave resultset calls. rs is expected to be closed try { rs1.next(); @@ -509,15 +415,7 @@ public void testTwoResultsetsSameStmt() throws SQLException { rs1.close(); rs2.next(); rs2.verify(table2); - } - finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - terminateVariation(); + rs2.close(); } } @@ -528,12 +426,10 @@ public void testTwoResultsetsSameStmt() throws SQLException { */ @Test public void testResultSetAndCloseStmt() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { stmt.close(); // this should close the resultSet try { @@ -542,10 +438,7 @@ public void testResultSetAndCloseStmt() throws SQLException { catch (SQLException e) { assertEquals(e.toString(), "com.microsoft.sqlserver.jdbc.SQLServerException: The result set is closed."); } - assertTrue(true, "Previouse one should have thrown exception!"); - } - finally { - terminateVariation(); + assertTrue(true, "Previous one should have thrown exception!"); } } @@ -557,18 +450,12 @@ public void testResultSetAndCloseStmt() throws SQLException { @Test public void testResultSetSelectMethod() throws SQLException { - try { - conn = new DBConnection(connectionString + ";selectMethod=cursor;"); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); - + String query = "SELECT * FROM " + table1.getEscapedTableName(); + try (DBConnection conn = new DBConnection(connectionString + ";selectMethod=cursor;"); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -579,34 +466,10 @@ public void testResultSetSelectMethod() throws SQLException { @AfterAll public static void terminate() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { stmt.execute("if object_id('" + table1.getEscapedTableName() + "','U') is not null" + " drop table " + table1.getEscapedTableName()); stmt.execute("if object_id('" + table2.getEscapedTableName() + "','U') is not null" + " drop table " + table2.getEscapedTableName()); } - finally { - terminateVariation(); - } - } - - /** - * cleanup after tests - * - * @throws SQLException - */ - public static void terminateVariation() throws SQLException { - if (conn != null && !conn.isClosed()) { - try { - conn.close(); - } - finally { - if (null != rs) - rs.close(); - if (null != stmt) - stmt.close(); - } - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java index 684bfd81d..0306d6f1d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java @@ -24,18 +24,14 @@ */ @RunWith(JUnitPlatform.class) public class bvtTestSetup extends AbstractTest { - private static DBConnection conn = null; - private static DBStatement stmt = null; static DBTable table1; static DBTable table2; @BeforeAll public static void init() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { // create tables table1 = new DBTable(true); stmt.createTable(table1); @@ -44,14 +40,5 @@ public static void init() throws SQLException { stmt.createTable(table2); stmt.populateTable(table2); } - finally { - if (null != stmt) { - stmt.close(); - } - if (null != conn && !conn.isClosed()) { - conn.close(); - } - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java index d0271714d..dad9c195f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -1,9 +1,12 @@ package com.microsoft.sqlserver.jdbc.callablestatement; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; @@ -17,6 +20,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; +import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.Utils; @@ -28,6 +32,7 @@ public class CallableStatementTest extends AbstractTest { private static String tableNameGUID = "uniqueidentifier_Table"; private static String outputProcedureNameGUID = "uniqueidentifier_SP"; private static String setNullProcedureName = "CallableStatementTest_setNull_SP"; + private static String inputParamsProcedureName = "CallableStatementTest_inputParams_SP"; private static Connection connection = null; private static Statement stmt = null; @@ -45,10 +50,12 @@ public static void setupTest() throws SQLException { Utils.dropTableIfExists(tableNameGUID, stmt); Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); Utils.dropProcedureIfExists(setNullProcedureName, stmt); + Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); - createGUIDTable(); - createGUIDStoredProcedure(); - createSetNullPreocedure(); + createGUIDTable(stmt); + createGUIDStoredProcedure(stmt); + createSetNullPreocedure(stmt); + createInputParamsProcedure(stmt); } /** @@ -59,17 +66,14 @@ public static void setupTest() throws SQLException { @Test public void getStringGUIDTest() throws SQLException { - SQLServerCallableStatement callableStatement = null; - try { - String sql = "{call " + outputProcedureNameGUID + "(?)}"; - - callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql); + String sql = "{call " + outputProcedureNameGUID + "(?)}"; + + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql)) { UUID originalValue = UUID.randomUUID(); callableStatement.registerOutParameter(1, microsoft.sql.Types.GUID); callableStatement.setObject(1, originalValue.toString(), microsoft.sql.Types.GUID); - callableStatement.execute(); String retrievedValue = callableStatement.getString(1); @@ -77,11 +81,6 @@ public void getStringGUIDTest() throws SQLException { assertEquals(originalValue.toString().toLowerCase(), retrievedValue.toLowerCase()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } /** @@ -93,17 +92,14 @@ public void getStringGUIDTest() throws SQLException { public void getSetNullWithTypeVarchar() throws SQLException { String polishchar = "\u0143"; - SQLServerCallableStatement cs = null; - SQLServerCallableStatement cs2 = null; - try { - SQLServerDataSource ds = new SQLServerDataSource(); - ds.setURL(connectionString); - ds.setSendStringParametersAsUnicode(true); - connection = ds.getConnection(); - - String sql = "{? = call " + setNullProcedureName + " (?,?)}"; + SQLServerDataSource ds = new SQLServerDataSource(); + ds.setURL(connectionString); + ds.setSendStringParametersAsUnicode(true); + String sql = "{? = call " + setNullProcedureName + " (?,?)}"; + try (Connection connection = ds.getConnection(); + SQLServerCallableStatement cs = (SQLServerCallableStatement) connection.prepareCall(sql); + SQLServerCallableStatement cs2 = (SQLServerCallableStatement) connection.prepareCall(sql)){ - cs = (SQLServerCallableStatement) connection.prepareCall(sql); cs.registerOutParameter(1, Types.INTEGER); cs.setString(2, polishchar); cs.setString(3, null); @@ -112,7 +108,6 @@ public void getSetNullWithTypeVarchar() throws SQLException { String expected = cs.getString(3); - cs2 = (SQLServerCallableStatement) connection.prepareCall(sql); cs2.registerOutParameter(1, Types.INTEGER); cs2.setString(2, polishchar); cs2.setNull(3, Types.VARCHAR); @@ -120,19 +115,51 @@ public void getSetNullWithTypeVarchar() throws SQLException { cs2.execute(); String actual = cs2.getString(3); - + assertEquals(expected, actual); } - finally { - if (null != cs) { - cs.close(); - } - if (null != cs2) { - cs2.close(); + } + + + /** + * recognize parameter names with and without leading '@' + * + * @throws SQLException + */ + @Test + public void inputParamsTest() throws SQLException { + String call = "{CALL " + inputParamsProcedureName + " (?,?)}"; + ResultSet rs = null; + + // the historical way: no leading '@', parameter names respected (not positional) + CallableStatement cs1 = connection.prepareCall(call); + cs1.setString("p2", "bar"); + cs1.setString("p1", "foo"); + rs = cs1.executeQuery(); + rs.next(); + assertEquals("foobar", rs.getString(1)); + + // the "new" way: leading '@', parameter names still respected (not positional) + CallableStatement cs2 = connection.prepareCall(call); + cs2.setString("@p2", "world!"); + cs2.setString("@p1", "Hello "); + rs = cs2.executeQuery(); + rs.next(); + assertEquals("Hello world!", rs.getString(1)); + + // sanity check: unrecognized parameter name + CallableStatement cs3 = connection.prepareCall(call); + try { + cs3.setString("@whatever", "junk"); + fail("SQLServerException should have been thrown"); + } catch (SQLServerException sse) { + if (!sse.getMessage().startsWith("Parameter @whatever was not defined")) { + fail("Unexpected content in exception message"); } } - } + } + /** * Cleanup after test * @@ -143,6 +170,7 @@ public static void cleanup() throws SQLException { Utils.dropTableIfExists(tableNameGUID, stmt); Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); Utils.dropProcedureIfExists(setNullProcedureName, stmt); + Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); if (null != stmt) { stmt.close(); @@ -152,17 +180,30 @@ public static void cleanup() throws SQLException { } } - private static void createGUIDStoredProcedure() throws SQLException { + private static void createGUIDStoredProcedure(Statement stmt) throws SQLException { String sql = "CREATE PROCEDURE " + outputProcedureNameGUID + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " + tableNameGUID + ";"; stmt.execute(sql); } - private static void createGUIDTable() throws SQLException { + private static void createGUIDTable(Statement stmt) throws SQLException { String sql = "CREATE TABLE " + tableNameGUID + " (c1 uniqueidentifier null)"; stmt.execute(sql); } - private static void createSetNullPreocedure() throws SQLException { + private static void createSetNullPreocedure(Statement stmt) throws SQLException { stmt.execute("create procedure " + setNullProcedureName + " (@p1 nvarchar(255), @p2 nvarchar(255) output) as select @p2=@p1 return 0"); } + + private static void createInputParamsProcedure(Statement stmt) throws SQLException { + String sql = + "CREATE PROCEDURE [dbo].[CallableStatementTest_inputParams_SP] " + + " @p1 nvarchar(max) = N'parameter1', " + + " @p2 nvarchar(max) = N'parameter2' " + + "AS " + + "BEGIN " + + " SET NOCOUNT ON; " + + " SELECT @p1 + @p2 AS result; " + + "END "; + stmt.execute(sql); + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java index c8a415540..2acf5f002 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -123,8 +123,7 @@ public void testEncryptedConnection() throws SQLException { ds.setEncrypt(true); ds.setTrustServerCertificate(true); ds.setPacketSize(8192); - Connection con = ds.getConnection(); - con.close(); + try(Connection con = ds.getConnection()) {} } @Test @@ -172,25 +171,25 @@ public void testConnectionEvents() throws SQLException { // Attach the Event listener and listen for connection events. MyEventListener myE = new MyEventListener(); - pooledConnection.addConnectionEventListener(myE); // ConnectionListener - // implements - // ConnectionEventListener - Connection con = pooledConnection.getConnection(); - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - - boolean exceptionThrown = false; - try { - // raise a severe exception and make sure that the connection is not - // closed. - stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + pooledConnection.addConnectionEventListener(myE); // ConnectionListener implements ConnectionEventListener + + try(Connection con = pooledConnection.getConnection(); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + + boolean exceptionThrown = false; + try { + // raise a severe exception and make sure that the connection is not + // closed. + stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + } + catch (Exception e) { + exceptionThrown = true; + } + assertTrue(exceptionThrown, "Expected exception is not thrown."); + + // Check to see if error occurred. + assertTrue(myE.errorOccurred, "Error occurred is not called."); } - catch (Exception e) { - exceptionThrown = true; - } - assertTrue(exceptionThrown, "Expected exception is not thrown."); - - // Check to see if error occurred. - assertTrue(myE.errorOccurred, "Error occurred is not called."); // make sure that connection is closed. } @@ -204,23 +203,18 @@ public void testConnectionPoolGetTwice() throws SQLException { // Attach the Event listener and listen for connection events. MyEventListener myE = new MyEventListener(); - pooledConnection.addConnectionEventListener(myE); // ConnectionListener - // implements - // ConnectionEventListener - - Connection con = pooledConnection.getConnection(); - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + pooledConnection.addConnectionEventListener(myE); // ConnectionListener implements ConnectionEventListener - // raise a non severe exception and make sure that the connection is not - // closed. + Connection con = pooledConnection.getConnection(); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + // raise a non severe exception and make sure that the connection is not closed. stmt.executeUpdate("RAISERROR ('foo', 3,1) WITH LOG"); - // not a serious error there should not be any errors. assertTrue(!myE.errorOccurred, "Error occurred is called."); // check to make sure that connection is not closed. - assertTrue(!con.isClosed(), "Connection is closed."); - - con.close(); + assertTrue(!con.isClosed(), "Connection is closed."); + stmt.close(); + con.close(); // check to make sure that connection is closed. assertTrue(con.isClosed(), "Connection is not closed."); } @@ -242,36 +236,34 @@ public void testConnectionClosed() throws SQLException { exceptionThrown = true; } assertTrue(exceptionThrown, "Expected exception is not thrown."); - + // check to make sure that connection is closed. assertTrue(con.isClosed(), "Connection is not closed."); } @Test public void testIsWrapperFor() throws SQLException, ClassNotFoundException { - Connection conn = DriverManager.getConnection(connectionString); - SQLServerConnection ssconn = (SQLServerConnection) conn; - boolean isWrapper; - isWrapper = ssconn.isWrapperFor(ssconn.getClass()); - assertTrue(isWrapper, "SQLServerConnection supports unwrapping"); - assertEquals(ssconn.TRANSACTION_SNAPSHOT, ssconn.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); - - isWrapper = ssconn.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); - assertTrue(isWrapper, "ISQLServerConnection supports unwrapping"); - ISQLServerConnection iSql = (ISQLServerConnection) ssconn.unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); - assertEquals(iSql.TRANSACTION_SNAPSHOT, iSql.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); - - ssconn.unwrap(Class.forName("java.sql.Connection")); - - conn.close(); + try(Connection conn = DriverManager.getConnection(connectionString); + SQLServerConnection ssconn = (SQLServerConnection) conn) { + boolean isWrapper; + isWrapper = ssconn.isWrapperFor(ssconn.getClass()); + assertTrue(isWrapper, "SQLServerConnection supports unwrapping"); + assertEquals(ssconn.TRANSACTION_SNAPSHOT, ssconn.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); + + isWrapper = ssconn.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + assertTrue(isWrapper, "ISQLServerConnection supports unwrapping"); + ISQLServerConnection iSql = (ISQLServerConnection) ssconn.unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + assertEquals(iSql.TRANSACTION_SNAPSHOT, iSql.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); + + ssconn.unwrap(Class.forName("java.sql.Connection")); + } } @Test public void testNewConnection() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - assertTrue(conn.isValid(0), "Newly created connection should be valid"); - - conn.close(); + try(SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + assertTrue(conn.isValid(0), "Newly created connection should be valid"); + } } @Test @@ -283,46 +275,46 @@ public void testClosedConnection() throws SQLException { @Test public void testNegativeTimeout() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - try { - conn.isValid(-42); - throw new Exception("No exception thrown with negative timeout"); - } - catch (SQLException e) { - assertEquals(e.getMessage(), "The query timeout value -42 is not valid.", "Wrong exception message"); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try { + conn.isValid(-42); + throw new Exception("No exception thrown with negative timeout"); + } + catch (SQLException e) { + assertEquals(e.getMessage(), "The query timeout value -42 is not valid.", "Wrong exception message"); + } } - - conn.close(); } @Test public void testDeadConnection() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), "Skipping test case on Azure SQL."); - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";responseBuffering=adaptive"); - Statement stmt = null; - - String tableName = RandomUtil.getIdentifier("Table"); - tableName = DBTable.escapeIdentifier(tableName); - - conn.setAutoCommit(false); - stmt = conn.createStatement(); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); - for (int i = 0; i < 80; i++) { - stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); - } - conn.commit(); - try { - stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " + tableName - + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); - } - catch (SQLServerException e) { - assertEquals(e.getMessage(), "Connection reset", "Unknown Exception"); - } - finally { - DriverManager.getConnection(connectionString).createStatement().execute("drop table " + tableName); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";responseBuffering=adaptive")) { + + Statement stmt = null; + String tableName = RandomUtil.getIdentifier("Table"); + tableName = DBTable.escapeIdentifier(tableName); + + conn.setAutoCommit(false); + stmt = conn.createStatement(); + stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); + for (int i = 0; i < 80; i++) { + stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); + } + conn.commit(); + try { + stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " + tableName + + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); + } + catch (SQLServerException e) { + assertEquals(e.getMessage(), "Connection reset", "Unknown Exception"); + } + finally { + DriverManager.getConnection(connectionString).createStatement().execute("drop table " + tableName); + } + assertEquals(conn.isValid(5), false, "Dead connection should be invalid"); } - assertEquals(conn.isValid(5), false, "Dead connection should be invalid"); } @Test diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java index 9645d5b95..f71da3f7f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java @@ -11,13 +11,13 @@ import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; -import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBTable; import com.microsoft.sqlserver.testframework.util.RandomUtil; @@ -32,26 +32,27 @@ public void testDatabaseMetaData() throws SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); - Connection con = ds.getConnection(); - - // drop function String sqlDropFunction = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo]." + functionName + "')" + "and xtype in (N'FN', N'IF', N'TF'))" + "drop function " + functionName; - con.createStatement().execute(sqlDropFunction); - - // create function String sqlCreateFunction = "CREATE FUNCTION " + functionName + " (@text varchar(8000), @delimiter varchar(20) = ' ') RETURNS @Strings TABLE " + "(position int IDENTITY PRIMARY KEY, value varchar(8000)) AS BEGIN INSERT INTO @Strings VALUES ('DDD') RETURN END "; - con.createStatement().execute(sqlCreateFunction); - - DatabaseMetaData md = con.getMetaData(); - ResultSet arguments = md.getProcedureColumns(null, null, null, "@TABLE_RETURN_VALUE"); - - if (arguments.next()) { - arguments.getString("COLUMN_NAME"); - arguments.getString("DATA_TYPE"); // call this function to make sure it does not crash + + try (Connection con = ds.getConnection(); + Statement stmt = con.createStatement()) { + // drop function + stmt.execute(sqlDropFunction); + // create function + stmt.execute(sqlCreateFunction); + + DatabaseMetaData md = con.getMetaData(); + try (ResultSet arguments = md.getProcedureColumns(null, null, null, "@TABLE_RETURN_VALUE")) { + + if (arguments.next()) { + arguments.getString("COLUMN_NAME"); + arguments.getString("DATA_TYPE"); // call this function to make sure it does not crash + } + } + stmt.execute(sqlDropFunction); } - - con.createStatement().execute(sqlDropFunction); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java index 08ba2a58a..57803a32e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java @@ -43,36 +43,34 @@ public void testNativeMSSQLDataSource() throws SQLException { @Test public void testSerialization() throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - ObjectOutput objectOutput = new ObjectOutputStream(outputStream); - - SQLServerDataSource ds = new SQLServerDataSource(); - ds.setLogWriter(new PrintWriter(new ByteArrayOutputStream())); - - objectOutput.writeObject(ds); - objectOutput.flush(); + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ObjectOutput objectOutput = new ObjectOutputStream(outputStream)) { + SQLServerDataSource ds = new SQLServerDataSource(); + ds.setLogWriter(new PrintWriter(new ByteArrayOutputStream())); + + objectOutput.writeObject(ds); + objectOutput.flush(); + } } @Test - public void testDSNormal() throws SQLServerException, ClassNotFoundException, IOException { + public void testDSNormal() throws ClassNotFoundException, IOException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); - Connection conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} ds = testSerial(ds); - conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} } @Test - public void testDSTSPassword() throws SQLServerException, ClassNotFoundException, IOException { + public void testDSTSPassword() throws ClassNotFoundException, IOException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); System.setProperty("java.net.preferIPv6Addresses", "true"); ds.setURL(connectionString); ds.setTrustStorePassword("wrong_password"); - Connection conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} ds = testSerial(ds); - try { - conn = ds.getConnection(); - } + try (Connection conn = ds.getConnection()) {} catch (SQLServerException e) { assertEquals("The DataSource trustStore password needs to be set.", e.getMessage()); } @@ -106,13 +104,16 @@ public void testInterfaceWrapping() throws ClassNotFoundException, SQLException } private SQLServerDataSource testSerial(SQLServerDataSource ds) throws IOException, ClassNotFoundException { - java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); - java.io.ObjectOutput objectOutput = new java.io.ObjectOutputStream(outputStream); - objectOutput.writeObject(ds); - objectOutput.flush(); - ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray())); - SQLServerDataSource dtn; - dtn = (SQLServerDataSource) in.readObject(); - return dtn; + try (java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); + java.io.ObjectOutput objectOutput = new java.io.ObjectOutputStream(outputStream)) { + objectOutput.writeObject(ds); + objectOutput.flush(); + + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray()))) { + SQLServerDataSource dtn; + dtn = (SQLServerDataSource) in.readObject(); + return dtn; + } + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java index 1c254b54b..1a51deb34 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -59,17 +59,15 @@ public void testPooling() throws SQLException { XADataSource1.setDatabaseName("tempdb"); PooledConnection pc = XADataSource1.getPooledConnection(); - Connection conn = pc.getConnection(); - - // create table in tempdb database - conn.createStatement().execute("create table [" + tempTableName + "] (myid int)"); - conn.createStatement().execute("insert into [" + tempTableName + "] values (1)"); - conn.close(); - - conn = pc.getConnection(); + try (Connection conn = pc.getConnection()) { + + // create table in tempdb database + conn.createStatement().execute("create table [" + tempTableName + "] (myid int)"); + conn.createStatement().execute("insert into [" + tempTableName + "] values (1)"); + } boolean tempTableFileRemoved = false; - try { + try (Connection conn = pc.getConnection()) { conn.createStatement().executeQuery("select * from [" + tempTableName + "]"); } catch (SQLServerException e) { @@ -109,12 +107,12 @@ public void testConnectionPoolConnFunctions() throws SQLException { ds.setURL(connectionString); PooledConnection pc = ds.getPooledConnection(); - Connection con = pc.getConnection(); - - Statement statement = con.createStatement(); - statement.execute(sql1); - statement.execute(sql2); - con.clearWarnings(); + try (Connection con = pc.getConnection(); + Statement statement = con.createStatement()) { + statement.execute(sql1); + statement.execute(sql2); + con.clearWarnings(); + } pc.close(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java index da20156c7..2e1fe11f6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -378,6 +378,23 @@ public void testIntStoredProcedure() throws SQLServerException { Cstatement.close(); } } + + /** + * Test for allowing duplicate columns + * + * @throws SQLServerException + */ + @Test + public void testDuplicateColumn() throws SQLServerException { + tvp = new SQLServerDataTable(); + tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); + tvp.addColumnMetadata("c2", microsoft.sql.Types.SQL_VARIANT); + try { + tvp.addColumnMetadata("c2", microsoft.sql.Types.SQL_VARIANT); + } catch (SQLServerException e) { + assertEquals(e.getMessage(), "A column name c2 already belongs to this SQLServerDataTable."); + } + } private static String[] createNumericValues() { Boolean C1_BIT; diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java index 95f2962c2..e93f1c150 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java @@ -22,6 +22,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -31,7 +32,6 @@ @RunWith(JUnitPlatform.class) public class CallableMixedTest extends AbstractTest { Connection connection = null; - Statement statement = null; String tableN = RandomUtil.getIdentifier("TFOO3"); String procN = RandomUtil.getIdentifier("SPFOO3"); String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); @@ -39,71 +39,62 @@ public class CallableMixedTest extends AbstractTest { /** * Tests Callable mix + * * @throws SQLException */ @Test @DisplayName("Test CallableMix") public void datatypesTest() throws SQLException { - connection = DriverManager.getConnection(connectionString); - statement = connection.createStatement(); + try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement();) { - try { - statement.executeUpdate("DROP TABLE " + tableName); - statement.executeUpdate(" DROP PROCEDURE " + procName); - } - catch (Exception e) { - } + statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); + statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); - statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); - statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); - statement.close(); - Statement stmt = connection.createStatement(); - stmt.executeUpdate("CREATE PROCEDURE " + procName - + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " - + tableName + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - stmt.close(); + statement.executeUpdate("CREATE PROCEDURE " + procName + + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " + + tableName + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }"); - callableStatement.registerOutParameter((int) 1, (int) 4); - callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); - callableStatement.registerOutParameter((int) 3, (int) 4); - callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); - callableStatement.registerOutParameter((int) 5, (int) 5); - callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); + try (CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }")) { + callableStatement.registerOutParameter((int) 1, (int) 4); + callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); + callableStatement.registerOutParameter((int) 3, (int) 4); + callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); + callableStatement.registerOutParameter((int) 5, (int) 5); + callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); - // get results and a value - ResultSet rs = callableStatement.executeQuery(); - rs.next(); + // get results and a value + ResultSet rs = callableStatement.executeQuery(); + rs.next(); - assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); + assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); - // do nothing and reexecute - rs = callableStatement.executeQuery(); - // get the param without getting the resultset - rs = callableStatement.executeQuery(); - assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); + // do nothing and reexecute + rs = callableStatement.executeQuery(); + // get the param without getting the resultset + rs = callableStatement.executeQuery(); + assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); - rs = callableStatement.executeQuery(); - rs.next(); + rs = callableStatement.executeQuery(); + rs.next(); - assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); - rs = callableStatement.executeQuery(); - callableStatement.close(); - rs.close(); - stmt.close(); - terminateVariation(); + assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); + rs = callableStatement.executeQuery(); + rs.close(); + } + terminateVariation(statement); + } } - - private void terminateVariation() throws SQLException { - statement = connection.createStatement(); - statement.executeUpdate("DROP TABLE " + tableName); - statement.executeUpdate(" DROP PROCEDURE " + procName); - statement.close(); - connection.close(); + /** + * Cleanups + * + * @throws SQLException + */ + private void terminateVariation(Statement statement) throws SQLException { + Utils.dropTableIfExists(tableName, statement); + Utils.dropProcedureIfExists(procName, statement); } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java index cc9e0e69f..6e3563101 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java @@ -32,6 +32,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; /** * Testing with LimitEscape queries @@ -782,13 +783,10 @@ public static void afterAll() throws Exception { Statement stmt = conn.createStatement(); try { - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t1', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t1"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t2', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t2"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t3', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t3"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t4', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t4"); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t4", stmt); } catch (Exception ex) { fail(ex.toString()); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java index 43b0bccc1..54ebcdde2 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java @@ -10,7 +10,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; +import java.sql.Connection; +import java.sql.DriverManager; import java.sql.ResultSet; +import java.sql.Statement; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; @@ -21,6 +24,7 @@ import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; +import com.microsoft.sqlserver.testframework.Utils; /** * Testing merge queries @@ -44,52 +48,42 @@ public class MergeTest extends AbstractTest { + "VALUES (SOURCE.CricketTeamID, SOURCE.CricketTeamCountry, SOURCE.CricketTeamContinent) " + "WHEN NOT MATCHED BY SOURCE THEN DELETE;"; - /** * Merge test + * * @throws Exception */ @Test @DisplayName("Merge Test") public void runTest() throws Exception { - DBConnection conn = new DBConnection(connectionString); - if (conn.getServerVersion() >= 10) { - DBStatement stmt = conn.createStatement(); - stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - stmt.executeUpdate(setupTables); - stmt.executeUpdate(mergeCmd2); - int updateCount = stmt.getUpdateCount(); - assertEquals(updateCount, 3, "Received the wrong update count!"); - - if (null != stmt) { - stmt.close(); - } - if (null != conn) { - conn.close(); + try (DBConnection conn = new DBConnection(connectionString)) { + if (conn.getServerVersion() >= 10) { + try (DBStatement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);) { + stmt.executeUpdate(setupTables); + stmt.executeUpdate(mergeCmd2); + int updateCount = stmt.getUpdateCount(); + assertEquals(updateCount, 3, "Received the wrong update count!"); + + } } } } - + /** * Clean up + * * @throws Exception */ @AfterAll public static void afterAll() throws Exception { - DBConnection conn = new DBConnection(connectionString); - DBStatement stmt = conn.createStatement(); - try { - stmt.executeUpdate("IF OBJECT_ID (N'dbo.CricketTeams', N'U') IS NOT NULL DROP TABLE dbo.CricketTeams"); - } - catch (Exception ex) { - fail(ex.toString()); - } - finally { - stmt.close(); - conn.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists("dbo.CricketTeams", stmt); + } + catch (Exception ex) { + fail(ex.toString()); + } } - } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java index be8139e39..2ee818313 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java @@ -32,87 +32,99 @@ */ @RunWith(JUnitPlatform.class) public class NamedParamMultiPartTest extends AbstractTest { - private static final String dataPut = "eminem "; + private static final String dataPut = "eminem"; private static Connection connection = null; - private static CallableStatement cs = null; + String procedureName = "mystoredproc"; /** * setup + * * @throws SQLException */ @BeforeAll public static void beforeAll() throws SQLException { connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement(); - Utils.dropProcedureIfExists("mystoredproc", statement); - statement.executeUpdate("CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); - statement.close(); - } + try (Statement statement = connection.createStatement()) { + Utils.dropProcedureIfExists("mystoredproc", statement); + statement.executeUpdate("CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); + } + } + /** * Stored procedure call + * * @throws Exception */ @Test public void update1() throws Exception { - cs = connection.prepareCall("{ CALL [mystoredproc] (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - String data = cs.getString("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + String data = cs.getString("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update2() throws Exception { - cs = connection.prepareCall("{ CALL [dbo].[mystoredproc] (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update3() throws Exception { String catalog = connection.getCatalog(); String storedproc = "[" + catalog + "]" + ".[dbo].[mystoredproc]"; - cs = connection.prepareCall("{ CALL " + storedproc + " (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update4() throws Exception { - cs = connection.prepareCall("{ CALL mystoredproc (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update5() throws Exception { - cs = connection.prepareCall("{ CALL dbo.mystoredproc (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** @@ -122,29 +134,29 @@ public void update5() throws Exception { @Test public void update6() throws Exception { String catalog = connection.getCatalog(); - String storedproc = catalog + ".dbo.mystoredproc"; - cs = connection.prepareCall("{ CALL " + storedproc + " (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + String storedproc = catalog + ".dbo." + procedureName; + try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Clean up + * + * @throws SQLException */ @AfterAll - public static void afterAll() { - try { - if (null != connection) { + public static void afterAll() throws SQLException { + try (Statement stmt = connection.createStatement()) { + Utils.dropProcedureIfExists("mystoredproc", stmt); + } + finally { + if (connection != null) { connection.close(); } - if (null != cs) { - cs.close(); - } - } - catch (SQLException e) { - fail(e.toString()); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java index 15fce3fe5..7d786dc46 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java @@ -30,6 +30,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerParameterMetaData; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -1380,16 +1381,17 @@ public void testComplexQueryWithMultipleTables() throws SQLServerException { */ @AfterAll public static void dropTables() throws SQLException { - stmt.execute("if object_id('" + nameTable + "','U') is not null" + " drop table " + nameTable); - stmt.execute("if object_id('" + phoneNumberTable + "','U') is not null" + " drop table " + phoneNumberTable); - stmt.execute("if object_id('" + mergeNameDesTable + "','U') is not null" + " drop table " + mergeNameDesTable); - stmt.execute("if object_id('" + numericTable + "','U') is not null" + " drop table " + numericTable); - stmt.execute("if object_id('" + charTable + "','U') is not null" + " drop table " + charTable); - stmt.execute("if object_id('" + charTable2 + "','U') is not null" + " drop table " + charTable2); - stmt.execute("if object_id('" + binaryTable + "','U') is not null" + " drop table " + binaryTable); - stmt.execute("if object_id('" + dateAndTimeTable + "','U') is not null" + " drop table " + dateAndTimeTable); - stmt.execute("if object_id('" + multipleTypesTable + "','U') is not null" + " drop table " + multipleTypesTable); - stmt.execute("if object_id('" + spaceTable + "','U') is not null" + " drop table " + spaceTable); + Utils.dropTableIfExists(nameTable, stmt); + Utils.dropTableIfExists(phoneNumberTable, stmt); + Utils.dropTableIfExists(mergeNameDesTable, stmt); + Utils.dropTableIfExists(numericTable, stmt); + Utils.dropTableIfExists(phoneNumberTable, stmt); + Utils.dropTableIfExists(charTable, stmt); + Utils.dropTableIfExists(charTable2, stmt); + Utils.dropTableIfExists(binaryTable, stmt); + Utils.dropTableIfExists(dateAndTimeTable, stmt); + Utils.dropTableIfExists(multipleTypesTable, stmt); + Utils.dropTableIfExists(spaceTable, stmt); if (null != rs) { rs.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java index 626efeb99..7ce0773de 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java @@ -8,6 +8,7 @@ package com.microsoft.sqlserver.jdbc.unit.statement; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.sql.CallableStatement; import java.sql.Connection; @@ -16,6 +17,7 @@ import java.sql.SQLException; import java.sql.Statement; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; @@ -25,6 +27,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; /** * Test Poolable statements @@ -35,44 +38,60 @@ public class PoolableTest extends AbstractTest { /** * Poolable Test + * * @throws SQLException * @throws ClassNotFoundException */ @Test @DisplayName("Poolable Test") - public void poolableTest() throws SQLException, ClassNotFoundException { - Connection connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement(); - try { - // First get the default values - boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); - assertEquals(isPoolable, false, "SQLServerStatement should not be Poolable by default"); + public void poolableTest() throws SQLException, ClassNotFoundException { + try (Connection conn = DriverManager.getConnection(connectionString); Statement statement = conn.createStatement()) { + try { + // First get the default values + boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); + assertEquals(isPoolable, false, "SQLServerStatement should not be Poolable by default"); - PreparedStatement prepStmt = connection.prepareStatement("select 1"); - isPoolable = ((SQLServerPreparedStatement) prepStmt).isPoolable(); - assertEquals(isPoolable, true, "SQLServerPreparedStatement should be Poolable by default"); + try (PreparedStatement prepStmt = connection.prepareStatement("select 1")) { + isPoolable = ((SQLServerPreparedStatement) prepStmt).isPoolable(); + assertEquals(isPoolable, true, "SQLServerPreparedStatement should be Poolable by default"); + } + try (CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }");) { + isPoolable = ((SQLServerCallableStatement) callableStatement).isPoolable(); - CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }"); - isPoolable = ((SQLServerCallableStatement) callableStatement).isPoolable(); + assertEquals(isPoolable, true, "SQLServerCallableStatement should be Poolable by default"); - assertEquals(isPoolable, true, "SQLServerCallableStatement should be Poolable by default"); + // Now do couple of sets and gets - // Now do couple of sets and gets - - ((SQLServerCallableStatement) callableStatement).setPoolable(false); - assertEquals(((SQLServerCallableStatement) callableStatement).isPoolable(), false, "set did not work"); - callableStatement.close(); - - ((SQLServerStatement) statement).setPoolable(true); - assertEquals(((SQLServerStatement) statement).isPoolable(), true, "set did not work"); - statement.close(); + ((SQLServerCallableStatement) callableStatement).setPoolable(false); + assertEquals(((SQLServerCallableStatement) callableStatement).isPoolable(), false, "set did not work"); + } + ((SQLServerStatement) statement).setPoolable(true); + assertEquals(((SQLServerStatement) statement).isPoolable(), true, "set did not work"); + } + catch (UnsupportedOperationException e) { + assertEquals(System.getProperty("java.specification.version"), "1.5", "PoolableTest should be supported in anything other than 1.5"); + assertEquals(e.getMessage(), "This operation is not supported.", "Wrong exception message"); + } } - catch (UnsupportedOperationException e) { - assertEquals(System.getProperty("java.specification.version"), "1.5", "PoolableTest should be supported in anything other than 1.5"); - assertEquals(e.getMessage(), "This operation is not supported.", "Wrong exception message"); + } + + /** + * Clean up + * + * @throws Exception + */ + @AfterAll + public static void afterAll() throws Exception { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try { + Utils.dropProcedureIfExists("ProcName", stmt); + } + catch (Exception ex) { + fail(ex.toString()); + } } - } - + } + } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java index 715f1c457..afb311ae9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java @@ -1172,10 +1172,23 @@ public void testLargeMaxRowsJDBC42() throws Exception { } } + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(table1Name, stmt); + Utils.dropTableIfExists(table2Name, stmt); + } + catch (SQLException e) { + } + } + } } @Nested public class TCStatementCallable { + String name = RandomUtil.getIdentifier("p1"); + String procName = AbstractSQLGenerator.escapeIdentifier(name); /** * Tests CallableStatementMethods on jdbc41 @@ -1187,41 +1200,19 @@ public void testJdbc41CallableStatementMethods() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Prepare database setup - String name = RandomUtil.getIdentifier("p1"); - String procName = AbstractSQLGenerator.escapeIdentifier(name); try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - String query = "create procedure " + procName - + " @col1Value varchar(512) OUTPUT," - + " @col2Value int OUTPUT," - + " @col3Value float OUTPUT," - + " @col4Value decimal(10,5) OUTPUT," - + " @col5Value uniqueidentifier OUTPUT," - + " @col6Value xml OUTPUT," - + " @col7Value varbinary(max) OUTPUT," - + " @col8Value text OUTPUT," - + " @col9Value ntext OUTPUT," - + " @col10Value varbinary(max) OUTPUT," - + " @col11Value date OUTPUT," - + " @col12Value time OUTPUT," - + " @col13Value datetime2 OUTPUT," - + " @col14Value datetimeoffset OUTPUT" - + " AS BEGIN " - + " SET @col1Value = 'hello'" - + " SET @col2Value = 1" - + " SET @col3Value = 2.0" - + " SET @col4Value = 123.45" - + " SET @col5Value = '6F9619FF-8B86-D011-B42D-00C04FC964FF'" - + " SET @col6Value = ''" - + " SET @col7Value = 0x63C34D6BCAD555EB64BF7E848D02C376" - + " SET @col8Value = 'text'" - + " SET @col9Value = 'ntext'" - + " SET @col10Value = 0x63C34D6BCAD555EB64BF7E848D02C376" - + " SET @col11Value = '2017-05-19'" - + " SET @col12Value = '10:47:15.1234567'" - + " SET @col13Value = '2017-05-19T10:47:15.1234567'" - + " SET @col14Value = '2017-05-19T10:47:15.1234567+02:00'" - + " END"; + String query = "create procedure " + procName + " @col1Value varchar(512) OUTPUT," + " @col2Value int OUTPUT," + + " @col3Value float OUTPUT," + " @col4Value decimal(10,5) OUTPUT," + " @col5Value uniqueidentifier OUTPUT," + + " @col6Value xml OUTPUT," + " @col7Value varbinary(max) OUTPUT," + " @col8Value text OUTPUT," + " @col9Value ntext OUTPUT," + + " @col10Value varbinary(max) OUTPUT," + " @col11Value date OUTPUT," + " @col12Value time OUTPUT," + + " @col13Value datetime2 OUTPUT," + " @col14Value datetimeoffset OUTPUT" + " AS BEGIN " + " SET @col1Value = 'hello'" + + " SET @col2Value = 1" + " SET @col3Value = 2.0" + " SET @col4Value = 123.45" + + " SET @col5Value = '6F9619FF-8B86-D011-B42D-00C04FC964FF'" + " SET @col6Value = ''" + + " SET @col7Value = 0x63C34D6BCAD555EB64BF7E848D02C376" + " SET @col8Value = 'text'" + " SET @col9Value = 'ntext'" + + " SET @col10Value = 0x63C34D6BCAD555EB64BF7E848D02C376" + " SET @col11Value = '2017-05-19'" + + " SET @col12Value = '10:47:15.1234567'" + " SET @col13Value = '2017-05-19T10:47:15.1234567'" + + " SET @col14Value = '2017-05-19T10:47:15.1234567+02:00'" + " END"; stmt.execute(query); // Test JDBC 4.1 methods for CallableStatement @@ -1244,7 +1235,7 @@ public void testJdbc41CallableStatementMethods() throws Exception { assertEquals("hello", cstmt.getObject(1, String.class)); assertEquals("hello", cstmt.getObject("col1Value", String.class)); - + assertEquals(Integer.valueOf(1), cstmt.getObject(2, Integer.class)); assertEquals(Integer.valueOf(1), cstmt.getObject("col2Value", Integer.class)); @@ -1256,7 +1247,7 @@ public void testJdbc41CallableStatementMethods() throws Exception { // BigDecimal#equals considers the number of decimal places assertEquals(0, cstmt.getObject(4, BigDecimal.class).compareTo(new BigDecimal("123.45"))); assertEquals(0, cstmt.getObject("col4Value", BigDecimal.class).compareTo(new BigDecimal("123.45"))); - + assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), cstmt.getObject(5, UUID.class)); assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), cstmt.getObject("col5Value", UUID.class)); @@ -1264,16 +1255,18 @@ public void testJdbc41CallableStatementMethods() throws Exception { sqlXml = cstmt.getObject(6, SQLXML.class); try { assertEquals("", sqlXml.getString()); - } finally { + } + finally { sqlXml.free(); } Blob blob; blob = cstmt.getObject(7, Blob.class); try { - assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, - blob.getBytes(1, 16)); - } finally { + assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, + 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, blob.getBytes(1, 16)); + } + finally { blob.free(); } @@ -1281,7 +1274,8 @@ public void testJdbc41CallableStatementMethods() throws Exception { clob = cstmt.getObject(8, Clob.class); try { assertEquals("text", clob.getSubString(1, 4)); - } finally { + } + finally { clob.free(); } @@ -1289,12 +1283,13 @@ public void testJdbc41CallableStatementMethods() throws Exception { nclob = cstmt.getObject(9, NClob.class); try { assertEquals("ntext", nclob.getSubString(1, 5)); - } finally { + } + finally { nclob.free(); } - assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, - cstmt.getObject(10, byte[].class)); + assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, + (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, cstmt.getObject(10, byte[].class)); assertEquals(java.sql.Date.valueOf("2017-05-19"), cstmt.getObject(11, java.sql.Date.class)); assertEquals(java.sql.Date.valueOf("2017-05-19"), cstmt.getObject("col11Value", java.sql.Date.class)); @@ -1307,18 +1302,29 @@ public void testJdbc41CallableStatementMethods() throws Exception { assertEquals("2017-05-19 10:47:15.1234567 +02:00", cstmt.getObject(14, microsoft.sql.DateTimeOffset.class).toString()); assertEquals("2017-05-19 10:47:15.1234567 +02:00", cstmt.getObject("col14Value", microsoft.sql.DateTimeOffset.class).toString()); - } finally { + } + } + } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { Utils.dropProcedureIfExists(procName, stmt); } + catch (SQLException e) { + fail(e.toString()); + } } } + } @Nested public class TCStatementParam { String tableNameTemp = RandomUtil.getIdentifier("TCStatementParam"); private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); - String procNameTemp = RandomUtil.getIdentifier("p1"); + String procNameTemp = "TCStatementParam"; private final String procName = AbstractSQLGenerator.escapeIdentifier(procNameTemp); /** @@ -1339,9 +1345,8 @@ public void testStatementOutParamGetsTwice() throws Exception { log.fine("testStatementOutParamGetsTwice threw: " + e.getMessage()); } - Utils.dropProcedureIfExists("sp_ouputP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); ResultSet rs = stmt.getResultSet(); if (rs != null) { @@ -1351,7 +1356,7 @@ public void testStatementOutParamGetsTwice() throws Exception { else { assertEquals(stmt.isClosed(), false, "testStatementOutParamGetsTwice: statement should be open since no resultset."); } - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputP] (?,?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1372,7 +1377,6 @@ public void testStatementOutParamGetsTwice() throws Exception { else { assertEquals((stmt).isClosed(), false, "testStatementOutParamGetsTwice: statement should be open since no resultset."); } - Utils.dropProcedureIfExists("sp_ouputP", stmt); } @Test @@ -1380,11 +1384,10 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - Utils.dropProcedureIfExists("sp_ouputMP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputMP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT, @p4_smallint smallint OUTPUT, @p5_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint, @p5_smallint_out=@p4_smallint RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT, @p4_smallint smallint OUTPUT, @p5_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint, @p5_smallint_out=@p4_smallint RETURN @p2_smallint + 1"); - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputMP] (?,?, ?, ?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?, ?, ?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1401,8 +1404,6 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { assertEquals(cstmt.getInt(3), 34, "Wrong value"); assertEquals(cstmt.getInt(5), 24, "Wrong value"); assertEquals(cstmt.getInt(1), 35, "Wrong value"); - - Utils.dropProcedureIfExists("sp_ouputMP", stmt); } /** @@ -1415,11 +1416,10 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - Utils.dropProcedureIfExists("sp_ouputP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p3_smallint_out +1 RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p3_smallint_out +1 RETURN @p2_smallint + 1"); - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputP] (?,?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("1"), Types.SMALLINT); cstmt.setObject(3, Short.valueOf("100"), Types.SMALLINT); @@ -1432,8 +1432,6 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { cstmt.execute(); assertEquals(cstmt.getInt(1), 11, "Wrong value"); assertEquals(cstmt.getInt(3), 101, "Wrong value"); - - Utils.dropProcedureIfExists("sp_ouputP", stmt); } /** @@ -1447,18 +1445,6 @@ public void testResultSetParams() throws Exception { Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1473,19 +1459,6 @@ public void testResultSetParams() throws Exception { rs.next(); assertEquals(rs.getString(2), "hello", "Wrong value"); assertEquals(cstmt.getString(2), "hi", "Wrong value"); - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** @@ -1495,25 +1468,10 @@ public void testResultSetParams() throws Exception { */ @Test public void testResultSetNullParams() throws Exception { - String temp = RandomUtil.getIdentifier("RetestResultSetNullParams"); - String tableName = AbstractSQLGenerator.escapeIdentifier(temp); - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1531,19 +1489,6 @@ public void testResultSetNullParams() throws Exception { throw ex; } ; - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** @@ -1555,12 +1500,7 @@ public void testFailedToResumeTransaction() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; + stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0)"); stmt.executeUpdate("Insert into " + tableName + " values(1)"); @@ -1581,12 +1521,6 @@ public void testFailedToResumeTransaction() throws Exception { } catch (SQLException ex) { } - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; conn.close(); } @@ -1600,18 +1534,6 @@ public void testResultSetErrors() throws Exception { Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1631,45 +1553,20 @@ public void testResultSetErrors() throws Exception { ; assertEquals(null, cstmt.getString(2), "Wrong value"); - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** * Verify proper handling of row errors in ResultSets. */ @Test - @Disabled - //TODO: We are commenting this out due to random AppVeyor failures. We will investigate later. + @Disabled + // TODO: We are commenting this out due to random AppVeyor failures. We will investigate later. public void testRowError() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); // Set up everything Statement stmt = conn.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); stmt.executeUpdate("insert into " + tableName + " values(0)"); @@ -1757,22 +1654,22 @@ public void testRowError() throws Exception { testConn2.close(); testConn1.close(); } - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.close(); conn.close(); } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropProcedureIfExists(procName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } + } } @Nested @@ -1790,11 +1687,6 @@ private Connection createConnectionAndPopulateData() throws Exception { con = ds.getConnection(); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } stmt.executeUpdate("CREATE TABLE " + tableName + "(col1_int int PRIMARY KEY IDENTITY(1,1), col2_varchar varchar(200), col3_varchar varchar(20) SPARSE NULL, col4_smallint smallint SPARSE NULL, col5_xml XML COLUMN_SET FOR ALL_SPARSE_COLUMNS, col6_nvarcharMax NVARCHAR(MAX), col7_varcharMax VARCHAR(MAX))"); @@ -1804,19 +1696,15 @@ private Connection createConnectionAndPopulateData() throws Exception { return con; } - private void cleanup(Connection con) throws Exception { - try { - if (con == null || con.isClosed()) { - con = DriverManager.getConnection(connectionString); + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); } - - Utils.dropTableIfExists(tableName, con.createStatement()); - } - catch (SQLException e) { - } - finally { - if (con != null) - con.close(); } } @@ -1849,7 +1737,7 @@ public void testNBCROWNullsForLOBs() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1891,7 +1779,7 @@ public void testSparseColumnSetValues() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1934,7 +1822,7 @@ public void testSparseColumnSetIndex() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1946,66 +1834,64 @@ public void testSparseColumnSetIndex() throws Exception { */ @Test public void testSparseColumnSetForException() throws Exception { - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testSparseColumnSetForException skipped for Yukon"); + try (DBConnection conn = new DBConnection(connectionString)) { + if (conn.getServerVersion() <= 9.0) { + log.fine("testSparseColumnSetForException skipped for Yukon"); + } } - Connection con = null; - try { - con = createConnectionAndPopulateData(); - Statement stmt = con.createStatement(); - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } - catch (Exception e) { + con = createConnectionAndPopulateData(); + Statement stmt = con.createStatement(); - throw new SQLException("testSparseColumnSetForException threw exception: ", e); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } + catch (Exception e) { - } + throw new SQLException("testSparseColumnSetForException threw exception: ", e); - String selectQuery = "SELECT * FROM " + tableName; - ResultSet rs = stmt.executeQuery(selectQuery); - rs.next(); + } - SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - try { - // test that an exception is thrown when result set is closed - rs.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + String selectQuery = "SELECT * FROM " + tableName; + ResultSet rs = stmt.executeQuery(selectQuery); + rs.next(); - // test that an exception is thrown when statement is closed - try { - rs = stmt.executeQuery(selectQuery); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + try { + // test that an exception is thrown when result set is closed + rs.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); + } + catch (SQLException e) { + } - assertEquals(stmt.isClosed(), true, "testSparseColumnSetForException: statement should be closed since resultset is closed."); - stmt.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + // test that an exception is thrown when statement is closed + try { + rs = stmt.executeQuery(selectQuery); + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - // test that an exception is thrown when connection is closed - try { - rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - con.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + assertEquals(stmt.isClosed(), true, "testSparseColumnSetForException: statement should be closed since resultset is closed."); + stmt.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); } - finally { - cleanup(con); + catch (SQLException e) { + } + + // test that an exception is thrown when connection is closed + try { + rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + con.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); } + catch (SQLException e) { + } + } /** @@ -2053,7 +1939,7 @@ public void testNBCRowForAllNulls() throws Exception { } finally { - cleanup(con); + terminate(); } } @@ -2159,7 +2045,7 @@ public void testNBCROWWithRandomAccess() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -2376,24 +2262,7 @@ private void setup() throws Exception { Connection con = DriverManager.getConnection(connectionString); con.setAutoCommit(false); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } - try { - Utils.dropTableIfExists(table2Name, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } - try { - Utils.dropProcedureIfExists(sprocName, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } + try { stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + "') drop trigger " + triggerName); } @@ -2499,6 +2368,20 @@ public void testStatementInsertExecInsert() throws Exception { // which should have affected 1 (new) row in tableName. assertEquals(updateCount, 1, "Wrong update count"); } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropTableIfExists(table2Name, stmt); + Utils.dropProcedureIfExists(sprocName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } + } } @Nested @@ -2514,11 +2397,7 @@ private void setup() throws Exception { Connection con = DriverManager.getConnection(connectionString); con.setAutoCommit(false); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } + try { stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + "') drop trigger " + triggerName); } @@ -2704,6 +2583,18 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Excep pstmt.close(); con.close(); } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } + } } @Nested @@ -2728,12 +2619,6 @@ private void setup() throws Exception { throw new SQLException("setup threw exception: ", e); } - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT primary key)"); for (int i = 0; i < NUM_ROWS; i++) stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); @@ -2752,26 +2637,36 @@ private void setup() throws Exception { @Test public void testNoCountWithExecute() throws Exception { // Ensure lastUpdateCount=true... - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); - Statement stmt = con.createStatement(); - boolean isResultSet = stmt - .execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); + Statement stmt = con.createStatement();) { - assertEquals(true, isResultSet, "execute() said first result was an update count"); + boolean isResultSet = stmt + .execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); - ResultSet rs = stmt.getResultSet(); - while (rs.next()) - ; - rs.close(); + assertEquals(true, isResultSet, "execute() said first result was an update count"); - boolean moreResults = stmt.getMoreResults(); - assertEquals(false, moreResults, "next result is a ResultSet?"); + ResultSet rs = stmt.getResultSet(); + while (rs.next()); + rs.close(); - int updateCount = stmt.getUpdateCount(); - assertEquals(-1, updateCount, "only one result was expected..."); + boolean moreResults = stmt.getMoreResults(); + assertEquals(false, moreResults, "next result is a ResultSet?"); - stmt.close(); - con.close(); + int updateCount = stmt.getUpdateCount(); + assertEquals(-1, updateCount, "only one result was expected..."); + } + } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } } } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java index 51e0c7aa2..a6ae11d07 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java @@ -21,7 +21,7 @@ /* * Wrapper class for SQLServerConnection */ -public class DBConnection extends AbstractParentWrapper { +public class DBConnection extends AbstractParentWrapper implements AutoCloseable { private double serverversion = 0; // TODO: add Isolation Level diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java index 0851f3907..d281effca 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java @@ -36,7 +36,7 @@ * */ -public class DBResultSet extends AbstractParentWrapper { +public class DBResultSet extends AbstractParentWrapper implements AutoCloseable { // TODO: add cursors // TODO: add resultSet level holdability diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java index 8d4787120..00b006026 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java @@ -21,7 +21,7 @@ * @author Microsoft * */ -public class DBStatement extends AbstractParentWrapper { +public class DBStatement extends AbstractParentWrapper implements AutoCloseable{ // TODO: support PreparedStatement and CallableStatement // TODO: add stmt level holdability @@ -120,7 +120,7 @@ public void close() throws SQLException { if ((null != dbresultSet) && null != ((ResultSet) dbresultSet.product())) { ((ResultSet) dbresultSet.product()).close(); } - statement.close(); + //statement.close(); } /** From a10b9d7d49d4504cc421448d6b1c94c09f79d45a Mon Sep 17 00:00:00 2001 From: ulvii Date: Thu, 19 Oct 2017 12:44:44 -0700 Subject: [PATCH 48/68] Add 6.3.5-SNAPSHOT to pom file (#530) * add snapshot to pom file --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8c39911c9..9fe11fb53 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.4 + 6.3.5-SNAPSHOT jar From 5693c391fe5413f54bffc5aee6b4e967ed200887 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Thu, 26 Oct 2017 18:06:51 -0700 Subject: [PATCH 49/68] revise the way that pom file uses version number --- pom.xml | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 9fe11fb53..a1f0fa24b 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.5-SNAPSHOT + 6.3.5.${jreVersion}-SNAPSHOT jar @@ -140,6 +140,11 @@ build41 + + + jre7 + + @@ -158,7 +163,6 @@ maven-jar-plugin 3.0.2 - ${project.artifactId}-${project.version}.jre7-preview ${project.build.outputDirectory}/META-INF/MANIFEST.MF @@ -171,9 +175,15 @@ build42 + true + + + jre8 + + @@ -192,7 +202,6 @@ maven-jar-plugin 3.0.2 - ${project.artifactId}-${project.version}.jre8-preview ${project.build.outputDirectory}/META-INF/MANIFEST.MF From c231b11403570fdf5dc112bb2814398b05ad5b25 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Fri, 27 Oct 2017 12:54:29 -0700 Subject: [PATCH 50/68] add -preview --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a1f0fa24b..a8ccbadda 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.5.${jreVersion}-SNAPSHOT + 6.3.5-SNAPSHOT.${jreVersion}-preview jar From 93e0b181a8cd1d60998d628013b87ba7e29961cf Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Wed, 1 Nov 2017 11:11:28 -0700 Subject: [PATCH 51/68] Fix for static logger member in abstract class 'SQLServerClobBase' --- .../microsoft/sqlserver/jdbc/SQLServerClob.java | 15 ++++++--------- .../microsoft/sqlserver/jdbc/SQLServerNClob.java | 11 +++++------ 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java index a9556baf3..89ff484a8 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java @@ -35,9 +35,6 @@ public class SQLServerClob extends SQLServerClobBase implements Clob { private static final long serialVersionUID = 2872035282200133865L; - // Loggers should be class static to avoid lock contention with multiple threads - private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SQLServerClob"); - /** * Create a new CLOB * @@ -50,19 +47,19 @@ public class SQLServerClob extends SQLServerClobBase implements Clob { @Deprecated public SQLServerClob(SQLServerConnection connection, String data) { - super(connection, data, (null == connection) ? null : connection.getDatabaseCollation(), logger, null); + super(connection, data, (null == connection) ? null : connection.getDatabaseCollation(), null); if (null == data) throw new NullPointerException(SQLServerException.getErrString("R_cantSetNull")); } SQLServerClob(SQLServerConnection connection) { - super(connection, "", connection.getDatabaseCollation(), logger, null); + super(connection, "", connection.getDatabaseCollation(), null); } SQLServerClob(BaseInputStream stream, TypeInfo typeInfo) throws SQLServerException, UnsupportedEncodingException { - super(null, stream, typeInfo.getSQLCollation(), logger , typeInfo); + super(null, stream, typeInfo.getSQLCollation(), typeInfo); } final JDBCType getJdbcType() { @@ -91,7 +88,9 @@ abstract class SQLServerClobBase implements Serializable { private ArrayList activeStreams = new ArrayList<>(1); transient SQLServerConnection con; - private static Logger logger; + + private final Logger logger = Logger.getLogger(getClass().getName()); + final private String traceID = getClass().getName().substring(1 + getClass().getName().lastIndexOf('.')) + ":" + nextInstanceID(); final public String toString() { @@ -129,7 +128,6 @@ private String getDisplayClassName() { SQLServerClobBase(SQLServerConnection connection, Object data, SQLCollation collation, - Logger logger, TypeInfo typeInfo) { this.con = connection; if (data instanceof BaseInputStream) { @@ -140,7 +138,6 @@ private String getDisplayClassName() { } this.sqlCollation = collation; this.typeInfo = typeInfo; - SQLServerClobBase.logger = logger; if (logger.isLoggable(Level.FINE)) { String loggingInfo = (null != connection) ? connection.toString() : "null connection"; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNClob.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNClob.java index 213bc422b..7263b9144 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNClob.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerNClob.java @@ -10,23 +10,22 @@ import java.io.UnsupportedEncodingException; import java.sql.NClob; -import java.util.logging.Logger; /** * SQLServerNClob represents a National Character Set LOB object and implements java.sql.NClob. */ public final class SQLServerNClob extends SQLServerClobBase implements NClob { - // Loggers should be class static to avoid lock contention with multiple threads - private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SQLServerNClob"); - SQLServerNClob(SQLServerConnection connection) { - super(connection, "", connection.getDatabaseCollation(), logger, null); + private static final long serialVersionUID = 1L; + + SQLServerNClob(SQLServerConnection connection) { + super(connection, "", connection.getDatabaseCollation(), null); } SQLServerNClob(BaseInputStream stream, TypeInfo typeInfo) throws SQLServerException, UnsupportedEncodingException { - super(null, stream, typeInfo.getSQLCollation(), logger , typeInfo); + super(null, stream, typeInfo.getSQLCollation(), typeInfo); } final JDBCType getJdbcType() { From 5940cfc9f7c44ec5eee1f85561feb1a0bbd0c793 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Fri, 3 Nov 2017 13:55:15 -0700 Subject: [PATCH 52/68] fix handle not fund bug for metadata caching --- .../jdbc/SQLServerPreparedStatement.java | 252 ++++++++---------- 1 file changed, 113 insertions(+), 139 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 2437a82d0..259d253e9 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -51,6 +51,8 @@ public class SQLServerPreparedStatement extends SQLServerStatement implements ISQLServerPreparedStatement { /** Flag to indicate that it is an internal query to retrieve encryption metadata. */ boolean isInternalEncryptionQuery = false; + + boolean definitionChanged = false; /** delimiter for multiple statements in a single batch */ private static final int BATCH_STATEMENT_DELIMITER_TDS_71 = 0x80; @@ -326,6 +328,13 @@ private boolean buildPreparedStrings(Parameter[] params, String newTypeDefinitions = buildParamTypeDefinitions(params, renewDefinition); if (null != preparedTypeDefinitions && newTypeDefinitions.equals(preparedTypeDefinitions)) return false; + + if(preparedTypeDefinitions == null) { + definitionChanged = false; + } + else { + definitionChanged = true; + } preparedTypeDefinitions = newTypeDefinitions; @@ -486,6 +495,9 @@ final void processResponse(TDSReader tdsReader) throws SQLServerException { final void doExecutePreparedStatement(PrepStmtExecCmd command) throws SQLServerException { resetForReexecute(); + definitionChanged = false; + String cacahedPreparedTypeDefinitions = preparedTypeDefinitions; + // If this request might be a query (as opposed to an update) then make // sure we set the max number of rows and max field size for any ResultSet // that may be returned. @@ -524,33 +536,25 @@ final void doExecutePreparedStatement(PrepStmtExecCmd command) throws SQLServerE hasNewTypeDefinitions = buildPreparedStrings(inOutParam, true); } - // Retry execution if existing handle could not be re-used. - for(int attempt = 1; attempt <= 2; ++attempt) { - try { - // Re-use handle if available, requires parameter definitions which are not available until here. - if (reuseCachedHandle(hasNewTypeDefinitions, 1 < attempt)) { - hasNewTypeDefinitions = false; - } - - // Start the request and detach the response reader so that we can - // continue using it after we return. - TDSWriter tdsWriter = command.startRequest(TDS.PKT_RPC); - - doPrepExec(tdsWriter, inOutParam, hasNewTypeDefinitions, hasExistingTypeDefinitions); - - ensureExecuteResultsReader(command.startResponse(getIsResponseBufferingAdaptive())); - startResults(); - getNextResult(); - } - catch(SQLException e) { - if (retryBasedOnFailedReuseOfCachedHandle(e, attempt)) - continue; - else - throw e; - } - break; + if (cacahedPreparedTypeDefinitions != null && cacahedPreparedTypeDefinitions.equals(preparedTypeDefinitions)) { + definitionChanged = true; + cacahedPreparedTypeDefinitions = preparedTypeDefinitions; + } + + if (reuseCachedHandle(hasNewTypeDefinitions, false)) { + hasNewTypeDefinitions = false; } + // Start the request and detach the response reader so that we can + // continue using it after we return. + TDSWriter tdsWriter = command.startRequest(TDS.PKT_RPC); + + doPrepExec(tdsWriter, inOutParam, hasNewTypeDefinitions, hasExistingTypeDefinitions); + + ensureExecuteResultsReader(command.startResponse(getIsResponseBufferingAdaptive())); + startResults(); + getNextResult(); + if (EXECUTE_QUERY == executeMethod && null == resultSet) { SQLServerException.makeFromDriverError(connection, this, SQLServerException.getErrString("R_noResultset"), null, true); } @@ -559,15 +563,6 @@ else if (EXECUTE_UPDATE == executeMethod && null != resultSet) { } } - /** Should the execution be retried because the re-used cached handle could not be re-used due to server side state changes? */ - private boolean retryBasedOnFailedReuseOfCachedHandle(SQLException e, int attempt) { - // Only retry based on these error codes: - // 586: The prepared statement handle %d is not valid in this context. Please verify that current database, user default schema, and ANSI_NULLS and QUOTED_IDENTIFIER set options are not changed since the handle is prepared. - // 8179: Could not find prepared statement with handle %d. - // 99586: Error used for testing. - return 1 == attempt && (586 == e.getErrorCode() || 8179 == e.getErrorCode() || 99586 == e.getErrorCode()); - } - /** * Consume the OUT parameter for the statement object itself. * @@ -916,7 +911,10 @@ private void getParameterEncryptionMetadata(Parameter[] params) throws SQLServer /** Manage re-using cached handles */ private boolean reuseCachedHandle(boolean hasNewTypeDefinitions, boolean discardCurrentCacheItem) { - + if (definitionChanged) { + return false; + } + // No re-use of caching for cursorable statements (statements that WILL use sp_cursor*) if (isCursorable(executeMethod)) return false; @@ -2565,13 +2563,16 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th // Create the parameter array that we'll use for all the items in this batch. Parameter[] batchParam = new Parameter[inOutParam.length]; + definitionChanged = false; + String cacahedPreparedTypeDefinitions = preparedTypeDefinitions; + TDSWriter tdsWriter = null; while (numBatchesExecuted < numBatches) { // Fill in the parameter values for this batch Parameter paramValues[] = batchParamValues.get(numBatchesPrepared); assert paramValues.length == batchParam.length; System.arraycopy(paramValues, 0, batchParam, 0, paramValues.length); - + boolean hasExistingTypeDefinitions = preparedTypeDefinitions != null; boolean hasNewTypeDefinitions = buildPreparedStrings(batchParam, false); @@ -2589,6 +2590,11 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th } } + if (cacahedPreparedTypeDefinitions != null && cacahedPreparedTypeDefinitions.equals(preparedTypeDefinitions)) { + definitionChanged = true; + cacahedPreparedTypeDefinitions = preparedTypeDefinitions; + } + // Update the crypto metadata for this batch. if (0 < numBatchesExecuted) { // cryptoMetaBatch will be empty for non-AE connections/statements. @@ -2597,114 +2603,82 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th } } - // Retry execution if existing handle could not be re-used. - for(int attempt = 1; attempt <= 2; ++attempt) { - try { - - // Re-use handle if available, requires parameter definitions which are not available until here. - if (reuseCachedHandle(hasNewTypeDefinitions, 1 < attempt)) { - hasNewTypeDefinitions = false; - } - - if (numBatchesExecuted < numBatchesPrepared) { - // assert null != tdsWriter; - tdsWriter.writeByte((byte) nBatchStatementDelimiter); - } - else { - resetForReexecute(); - tdsWriter = batchCommand.startRequest(TDS.PKT_RPC); - } + if (reuseCachedHandle(hasNewTypeDefinitions, false)) { + hasNewTypeDefinitions = false; + } - // If we have to (re)prepare the statement then we must execute it so - // that we get back a (new) prepared statement handle to use to - // execute additional batches. - // - // We must always prepare the statement the first time through. - // But we may also need to reprepare the statement if, for example, - // the size of a batch's string parameter values changes such - // that repreparation is necessary. - ++numBatchesPrepared; - - if (doPrepExec(tdsWriter, batchParam, hasNewTypeDefinitions, hasExistingTypeDefinitions) || numBatchesPrepared == numBatches) { - ensureExecuteResultsReader(batchCommand.startResponse(getIsResponseBufferingAdaptive())); - - boolean retry = false; - while (numBatchesExecuted < numBatchesPrepared) { - // NOTE: - // When making changes to anything below, consider whether similar changes need - // to be made to Statement batch execution. - - startResults(); - - try { - // Get the first result from the batch. If there is no result for this batch - // then bail, leaving EXECUTE_FAILED in the current and remaining slots of - // the update count array. - if (!getNextResult()) - return; - - // If the result is a ResultSet (rather than an update count) then throw an - // exception for this result. The exception gets caught immediately below and - // translated into (or added to) a BatchUpdateException. - if (null != resultSet) { - SQLServerException.makeFromDriverError(connection, this, SQLServerException.getErrString("R_resultsetGeneratedForUpdate"), - null, false); - } - } - catch (SQLServerException e) { - // If the failure was severe enough to close the connection or roll back a - // manual transaction, then propagate the error up as a SQLServerException - // now, rather than continue with the batch. - if (connection.isSessionUnAvailable() || connection.rolledBackTransaction()) - throw e; - - // Retry if invalid handle exception. - if (retryBasedOnFailedReuseOfCachedHandle(e, attempt)) { - //reset number of batches prepare - numBatchesPrepared = numBatchesExecuted; - retry = true; - break; - } - - // Otherwise, the connection is OK and the transaction is still intact, - // so just record the failure for the particular batch item. - updateCount = Statement.EXECUTE_FAILED; - if (null == batchCommand.batchException) - batchCommand.batchException = e; - } - - // In batch execution, we have a special update count - // to indicate that no information was returned - batchCommand.updateCounts[numBatchesExecuted] = (-1 == updateCount) ? Statement.SUCCESS_NO_INFO : updateCount; - processBatch(); - - numBatchesExecuted++; - } - if(retry) - continue; + if (numBatchesExecuted < numBatchesPrepared) { + // assert null != tdsWriter; + tdsWriter.writeByte((byte) nBatchStatementDelimiter); + } + else { + resetForReexecute(); + tdsWriter = batchCommand.startRequest(TDS.PKT_RPC); + } - // Only way to proceed with preparing the next set of batches is if - // we successfully executed the previously prepared set. - assert numBatchesExecuted == numBatchesPrepared; - } - } - catch(SQLException e) { - if (retryBasedOnFailedReuseOfCachedHandle(e, attempt)) { - // Reset number of batches prepared. - numBatchesPrepared = numBatchesExecuted; - continue; - } - else if (null != batchCommand.batchException) { - // if batch exception occurred, loop out to throw the initial batchException - numBatchesExecuted = numBatchesPrepared; - attempt++; - continue; + // If we have to (re)prepare the statement then we must execute it so + // that we get back a (new) prepared statement handle to use to + // execute additional batches. + // + // We must always prepare the statement the first time through. + // But we may also need to reprepare the statement if, for example, + // the size of a batch's string parameter values changes such + // that repreparation is necessary. + ++numBatchesPrepared; + + if (doPrepExec(tdsWriter, batchParam, hasNewTypeDefinitions, hasExistingTypeDefinitions) || numBatchesPrepared == numBatches) { + ensureExecuteResultsReader(batchCommand.startResponse(getIsResponseBufferingAdaptive())); + + boolean retry = false; + while (numBatchesExecuted < numBatchesPrepared) { + // NOTE: + // When making changes to anything below, consider whether similar changes need + // to be made to Statement batch execution. + + startResults(); + + try { + // Get the first result from the batch. If there is no result for this batch + // then bail, leaving EXECUTE_FAILED in the current and remaining slots of + // the update count array. + if (!getNextResult()) + return; + + // If the result is a ResultSet (rather than an update count) then throw an + // exception for this result. The exception gets caught immediately below and + // translated into (or added to) a BatchUpdateException. + if (null != resultSet) { + SQLServerException.makeFromDriverError(connection, this, SQLServerException.getErrString("R_resultsetGeneratedForUpdate"), + null, false); + } } - else { - throw e; + catch (SQLServerException e) { + // If the failure was severe enough to close the connection or roll back a + // manual transaction, then propagate the error up as a SQLServerException + // now, rather than continue with the batch. + if (connection.isSessionUnAvailable() || connection.rolledBackTransaction()) + throw e; + + // Otherwise, the connection is OK and the transaction is still intact, + // so just record the failure for the particular batch item. + updateCount = Statement.EXECUTE_FAILED; + if (null == batchCommand.batchException) + batchCommand.batchException = e; } + + // In batch execution, we have a special update count + // to indicate that no information was returned + batchCommand.updateCounts[numBatchesExecuted] = (-1 == updateCount) ? Statement.SUCCESS_NO_INFO : updateCount; + processBatch(); + + numBatchesExecuted++; } - break; + if (retry) + continue; + + // Only way to proceed with preparing the next set of batches is if + // we successfully executed the previously prepared set. + assert numBatchesExecuted == numBatchesPrepared; } } } From 97a5cfc80278914bb64a3ca320da2f436cec8758 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Fri, 3 Nov 2017 14:04:37 -0700 Subject: [PATCH 53/68] fix tests --- .../unit/statement/PreparedStatementTest.java | 64 +++++++++++++++---- 1 file changed, 51 insertions(+), 13 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java index 944c79672..b25025561 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java @@ -8,12 +8,13 @@ package com.microsoft.sqlserver.jdbc.unit.statement; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.sql.BatchUpdateException; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; @@ -31,9 +32,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; +import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.util.RandomUtil; @RunWith(JUnitPlatform.class) public class PreparedStatementTest extends AbstractTest { @@ -172,32 +173,69 @@ public void testStatementPooling() throws SQLException { } } - try (SQLServerConnection con = (SQLServerConnection)DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { // Test behvaior with statement pooling. con.setStatementPoolingCacheSize(10); - + this.executeSQL(con, + "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';"); // Test with missing handle failures (fake). this.executeSQL(con, "CREATE TABLE #update1 (col INT);INSERT #update1 VALUES (1);"); - this.executeSQL(con, "CREATE PROC #updateProc1 AS UPDATE #update1 SET col += 1; IF EXISTS (SELECT * FROM #update1 WHERE col % 5 = 0) THROW 99586, 'Prepared handle GAH!', 1;"); + this.executeSQL(con, + "CREATE PROC #updateProc1 AS UPDATE #update1 SET col += 1; IF EXISTS (SELECT * FROM #update1 WHERE col % 5 = 0) RAISERROR(99586,16,1);"); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc1")) { for (int i = 0; i < 100; ++i) { - assertSame(1, pstmt.executeUpdate()); + try { + assertSame(1, pstmt.executeUpdate()); + } + catch (SQLServerException e) { + // Error "Prepared handle GAH" is expected to happen. But it should not terminate the execution with RAISERROR. + // Since the original "Could not find prepared statement with handle" error does not terminate the execution after it. + if (!e.getMessage().contains("Prepared handle GAH")) { + throw e; + } + } } } + // test updated value, should be 1 + 100 = 101 + // although executeUpdate() throws exception, update operation should be executed successfully. + try (ResultSet rs = con.createStatement().executeQuery("select * from #update1")) { + rs.next(); + assertSame(101, rs.getInt(1)); + } + // Test batching with missing handle failures (fake). + this.executeSQL(con, + "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';"); this.executeSQL(con, "CREATE TABLE #update2 (col INT);INSERT #update2 VALUES (1);"); - this.executeSQL(con, "CREATE PROC #updateProc2 AS UPDATE #update2 SET col += 1; IF EXISTS (SELECT * FROM #update2 WHERE col % 5 = 0) THROW 99586, 'Prepared handle GAH!', 1;"); + this.executeSQL(con, + "CREATE PROC #updateProc2 AS UPDATE #update2 SET col += 1; IF EXISTS (SELECT * FROM #update2 WHERE col % 5 = 0) RAISERROR(99586,16,1);"); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc2")) { - for (int i = 0; i < 100; ++i) + for (int i = 0; i < 100; ++i) { pstmt.addBatch(); + } + + int[] updateCounts = null; + try { + updateCounts = pstmt.executeBatch(); + } + catch (BatchUpdateException e) { + // Error "Prepared handle GAH" is expected to happen. But it should not terminate the execution with RAISERROR. + // Since the original "Could not find prepared statement with handle" error does not terminate the execution after it. + if (!e.getMessage().contains("Prepared handle GAH")) { + throw e; + } + } - int[] updateCounts = pstmt.executeBatch(); + // since executeBatch() throws exception, it does not return anthing. So updateCounts is still null. + assertSame(null, updateCounts); - // Verify update counts are correct - for (int i : updateCounts) { - assertSame(1, i); + // test updated value, should be 1 + 100 = 101 + // although executeBatch() throws exception, update operation should be executed successfully. + try (ResultSet rs = con.createStatement().executeQuery("select * from #update2")) { + rs.next(); + assertSame(101, rs.getInt(1)); } } } From 9ffd521b646068b556d29e2ba55554f68d8341fc Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Fri, 3 Nov 2017 18:01:15 -0700 Subject: [PATCH 54/68] fix failures in requesthandling test --- .../com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 259d253e9..f23c44e80 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -912,6 +912,7 @@ private void getParameterEncryptionMetadata(Parameter[] params) throws SQLServer /** Manage re-using cached handles */ private boolean reuseCachedHandle(boolean hasNewTypeDefinitions, boolean discardCurrentCacheItem) { if (definitionChanged) { + prepStmtHandle = -1; // so that hasPreparedStatementHandle() also returns false return false; } From 2cbd0654426b6d98f09a202b53848b86c92954e4 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Mon, 6 Nov 2017 09:47:04 -0800 Subject: [PATCH 55/68] remove prepStmtHandle = -1 which disables metadata caching, and added fix for BatchTriggerTest --- .../sqlserver/jdbc/SQLServerPreparedStatement.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index f23c44e80..de8d3f844 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -912,7 +912,6 @@ private void getParameterEncryptionMetadata(Parameter[] params) throws SQLServer /** Manage re-using cached handles */ private boolean reuseCachedHandle(boolean hasNewTypeDefinitions, boolean discardCurrentCacheItem) { if (definitionChanged) { - prepStmtHandle = -1; // so that hasPreparedStatementHandle() also returns false return false; } @@ -2654,6 +2653,11 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th } } catch (SQLServerException e) { + // if batch exception occurred, throw the initial batchException + if (null == batchCommand.batchException) { + throw e; + } + // If the failure was severe enough to close the connection or roll back a // manual transaction, then propagate the error up as a SQLServerException // now, rather than continue with the batch. From ab68580e7d8cb3767c27e026c894000f98a447df Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Mon, 6 Nov 2017 10:24:28 -0800 Subject: [PATCH 56/68] remove fix for BatchTriggerTest, it breaks PreparedStatementTest --- .../microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index de8d3f844..259d253e9 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2653,11 +2653,6 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th } } catch (SQLServerException e) { - // if batch exception occurred, throw the initial batchException - if (null == batchCommand.batchException) { - throw e; - } - // If the failure was severe enough to close the connection or roll back a // manual transaction, then propagate the error up as a SQLServerException // now, rather than continue with the batch. From 5c747516f4c2c45cd8a85401fd3d4b73874d6fd6 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Mon, 6 Nov 2017 14:38:10 -0800 Subject: [PATCH 57/68] fix hasPreparedStatementHandle() --- .../sqlserver/jdbc/SQLServerPreparedStatement.java | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 259d253e9..c37b9cf15 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -496,7 +496,6 @@ final void doExecutePreparedStatement(PrepStmtExecCmd command) throws SQLServerE resetForReexecute(); definitionChanged = false; - String cacahedPreparedTypeDefinitions = preparedTypeDefinitions; // If this request might be a query (as opposed to an update) then make // sure we set the max number of rows and max field size for any ResultSet @@ -536,11 +535,6 @@ final void doExecutePreparedStatement(PrepStmtExecCmd command) throws SQLServerE hasNewTypeDefinitions = buildPreparedStrings(inOutParam, true); } - if (cacahedPreparedTypeDefinitions != null && cacahedPreparedTypeDefinitions.equals(preparedTypeDefinitions)) { - definitionChanged = true; - cacahedPreparedTypeDefinitions = preparedTypeDefinitions; - } - if (reuseCachedHandle(hasNewTypeDefinitions, false)) { hasNewTypeDefinitions = false; } @@ -912,6 +906,7 @@ private void getParameterEncryptionMetadata(Parameter[] params) throws SQLServer /** Manage re-using cached handles */ private boolean reuseCachedHandle(boolean hasNewTypeDefinitions, boolean discardCurrentCacheItem) { if (definitionChanged) { + prepStmtHandle = -1; // so that hasPreparedStatementHandle() also returns false return false; } @@ -2564,7 +2559,6 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th Parameter[] batchParam = new Parameter[inOutParam.length]; definitionChanged = false; - String cacahedPreparedTypeDefinitions = preparedTypeDefinitions; TDSWriter tdsWriter = null; while (numBatchesExecuted < numBatches) { @@ -2590,11 +2584,6 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th } } - if (cacahedPreparedTypeDefinitions != null && cacahedPreparedTypeDefinitions.equals(preparedTypeDefinitions)) { - definitionChanged = true; - cacahedPreparedTypeDefinitions = preparedTypeDefinitions; - } - // Update the crypto metadata for this batch. if (0 < numBatchesExecuted) { // cryptoMetaBatch will be empty for non-AE connections/statements. From 9a54b6b1772c4fc6f964f1bc0dafee9f25b8f6a9 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Mon, 6 Nov 2017 15:47:06 -0800 Subject: [PATCH 58/68] add the fix for batch trigger --- .../sqlserver/jdbc/SQLServerPreparedStatement.java | 8 +++++--- .../jdbc/unit/statement/PreparedStatementTest.java | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index c37b9cf15..c2880db04 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2618,7 +2618,6 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th if (doPrepExec(tdsWriter, batchParam, hasNewTypeDefinitions, hasExistingTypeDefinitions) || numBatchesPrepared == numBatches) { ensureExecuteResultsReader(batchCommand.startResponse(getIsResponseBufferingAdaptive())); - boolean retry = false; while (numBatchesExecuted < numBatchesPrepared) { // NOTE: // When making changes to anything below, consider whether similar changes need @@ -2653,6 +2652,11 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th updateCount = Statement.EXECUTE_FAILED; if (null == batchCommand.batchException) batchCommand.batchException = e; + + // throw the initial batchException + if (null != batchCommand.batchException) { + throw e; + } } // In batch execution, we have a special update count @@ -2662,8 +2666,6 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th numBatchesExecuted++; } - if (retry) - continue; // Only way to proceed with preparing the next set of batches is if // we successfully executed the previously prepared set. diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java index b25025561..c43739b5d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java @@ -220,7 +220,7 @@ public void testStatementPooling() throws SQLException { try { updateCounts = pstmt.executeBatch(); } - catch (BatchUpdateException e) { + catch (SQLServerException e) { // Error "Prepared handle GAH" is expected to happen. But it should not terminate the execution with RAISERROR. // Since the original "Could not find prepared statement with handle" error does not terminate the execution after it. if (!e.getMessage().contains("Prepared handle GAH")) { From 705ebc1ef1404c9a584102ca23b429af121071b6 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Mon, 6 Nov 2017 17:35:41 -0800 Subject: [PATCH 59/68] fix "handle is not valid" error. If context changed once, metadata caching is disabled on the connection --- .../sqlserver/jdbc/SQLServerConnection.java | 3 +++ .../jdbc/SQLServerPreparedStatement.java | 2 +- .../sqlserver/jdbc/SQLServerStatement.java | 20 ++++++++++++++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index a8397b605..3e75d5581 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -83,6 +83,9 @@ // Note all the public functions in this class also need to be defined in SQLServerConnectionPoolProxy. public class SQLServerConnection implements ISQLServerConnection { + boolean contextIsAlreadyChanged = false; + boolean contextChanged = false; + long timerExpire; boolean attemptRefreshTokenLocked = false; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index c2880db04..2164578f3 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -905,7 +905,7 @@ private void getParameterEncryptionMetadata(Parameter[] params) throws SQLServer /** Manage re-using cached handles */ private boolean reuseCachedHandle(boolean hasNewTypeDefinitions, boolean discardCurrentCacheItem) { - if (definitionChanged) { + if (definitionChanged || connection.contextChanged) { prepStmtHandle = -1; // so that hasPreparedStatementHandle() also returns false return false; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java index 7f6d8e1d2..6c95bff86 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java @@ -800,6 +800,20 @@ final void setMaxRowsAndMaxFieldSize() throws SQLServerException { } } + /* + * check if context has been changed by monitoring statment call on the connection, since context is connection based. + */ + void checkIfContextChanged(String sql) { + if (connection.contextIsAlreadyChanged) { + return; + } + else if (sql.toUpperCase().contains("ANSI_NULLS") || sql.toUpperCase().contains("QUOTED_IDENTIFIER") || sql.toUpperCase().contains("USE") + || sql.toUpperCase().contains("DEFAULT_SCHEMA")) { + connection.contextIsAlreadyChanged = true; + connection.contextChanged = true; + } + } + final void doExecuteStatement(StmtExecCmd execCmd) throws SQLServerException { resetForReexecute(); @@ -811,6 +825,8 @@ final void doExecuteStatement(StmtExecCmd execCmd) throws SQLServerException { // call syntax is rewritten here as SQL exec syntax. String sql = ensureSQLSyntax(execCmd.sql); + checkIfContextChanged(sql); + // If this request might be a query (as opposed to an update) then make // sure we set the max number of rows and max field size for any ResultSet // that may be returned. @@ -914,7 +930,9 @@ private void doExecuteStatementBatch(StmtBatchExecCmd execCmd) throws SQLServerE tdsWriter.writeString(batchIter.next()); while (batchIter.hasNext()) { tdsWriter.writeString(" ; "); - tdsWriter.writeString(batchIter.next()); + String sql = batchIter.next(); + tdsWriter.writeString(sql); + checkIfContextChanged(sql); } // Start the response From 3ccdf0fa110bc5cb88ad3ddc4fe65f25d60b5df5 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Tue, 7 Nov 2017 16:58:57 -0800 Subject: [PATCH 60/68] clear cached prepared statement handle when pooled connection is removed --- .../com/microsoft/sqlserver/jdbc/SQLServerConnection.java | 6 ++++++ .../sqlserver/jdbc/SQLServerConnectionPoolProxy.java | 3 +++ 2 files changed, 9 insertions(+) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 3e75d5581..5247638c1 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -5763,6 +5763,12 @@ final void evictCachedPreparedStatementHandle(PreparedStatementHandle handle) { preparedStatementHandleCache.remove(handle.getKey()); } + final void clearCachedPreparedStatementHandle() { + if (null != preparedStatementHandleCache) { + preparedStatementHandleCache.clear(); + } + } + // Handle closing handles when removed from cache. final class PreparedStatementCacheEvictionListener implements EvictionListener { public void onEviction(Sha1HashKey key, PreparedStatementHandle handle) { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java index b180a11c9..3117ec403 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnectionPoolProxy.java @@ -168,6 +168,9 @@ public void run() { if (bIsOpen && (null != wrappedConnection)) { if (wrappedConnection.getConnectionLogger().isLoggable(Level.FINER)) wrappedConnection.getConnectionLogger().finer(toString() + " Connection proxy closed "); + + // clear cached prepared statement handle on this connection + wrappedConnection.clearCachedPreparedStatementHandle(); wrappedConnection.poolCloseEventNotify(); wrappedConnection = null; } From 8559a339e042d5b8cc76fb2aa57fe449a64057df Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Wed, 8 Nov 2017 17:34:13 -0800 Subject: [PATCH 61/68] merge the fix of batch trigger --- .../sqlserver/jdbc/SQLServerPreparedStatement.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 2164578f3..f467eadee 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2655,7 +2655,12 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th // throw the initial batchException if (null != batchCommand.batchException) { - throw e; + if (numBatchesExecuted < numBatchesPrepared) { + continue; + } + else { + throw e; + } } } From 1839edcc85c5f4d0ddf09c21ea3ecbb45686e528 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Wed, 8 Nov 2017 17:38:13 -0800 Subject: [PATCH 62/68] change back the test to catch BatchUpdateException exception --- .../sqlserver/jdbc/unit/statement/PreparedStatementTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java index c43739b5d..b25025561 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java @@ -220,7 +220,7 @@ public void testStatementPooling() throws SQLException { try { updateCounts = pstmt.executeBatch(); } - catch (SQLServerException e) { + catch (BatchUpdateException e) { // Error "Prepared handle GAH" is expected to happen. But it should not terminate the execution with RAISERROR. // Since the original "Could not find prepared statement with handle" error does not terminate the execution after it. if (!e.getMessage().contains("Prepared handle GAH")) { From 875f62af719b57f026a92ef85137df97a8209012 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Thu, 9 Nov 2017 13:28:23 -0800 Subject: [PATCH 63/68] disable metadata caching after switching database on connection directly --- .../java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 5247638c1..7caf1b172 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -3082,6 +3082,8 @@ final void poolCloseEventNotify() throws SQLServerException { checkClosed(); if (catalog != null) { connectionCommand("use " + Util.escapeSQLId(catalog), "setCatalog"); + contextIsAlreadyChanged = true; + contextChanged = true; sCatalog = catalog; } loggerExternal.exiting(getClassNameLogging(), "setCatalog"); From df89f02c954bacc925f2831adf6b7e48fc316006 Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Fri, 10 Nov 2017 17:33:30 -0800 Subject: [PATCH 64/68] process all batch first, then throw batch exception is there is one, otherwise throw sql server exception --- .../jdbc/SQLServerPreparedStatement.java | 205 +++++++++--------- 1 file changed, 103 insertions(+), 102 deletions(-) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index f467eadee..438ac92ac 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2561,120 +2561,121 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th definitionChanged = false; TDSWriter tdsWriter = null; - while (numBatchesExecuted < numBatches) { - // Fill in the parameter values for this batch - Parameter paramValues[] = batchParamValues.get(numBatchesPrepared); - assert paramValues.length == batchParam.length; - System.arraycopy(paramValues, 0, batchParam, 0, paramValues.length); - - boolean hasExistingTypeDefinitions = preparedTypeDefinitions != null; - boolean hasNewTypeDefinitions = buildPreparedStrings(batchParam, false); - - // Get the encryption metadata for the first batch only. - if ((0 == numBatchesExecuted) && (Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection)) && (0 < batchParam.length) - && !isInternalEncryptionQuery && !encryptionMetadataIsRetrieved) { - getParameterEncryptionMetadata(batchParam); - - // fix an issue when inserting unicode into non-encrypted nchar column using setString() and AE is on on Connection - buildPreparedStrings(batchParam, true); - - // Save the crypto metadata retrieved for the first batch. We will re-use these for the rest of the batches. - for (Parameter aBatchParam : batchParam) { - cryptoMetaBatch.add(aBatchParam.cryptoMeta); + try { + while (numBatchesExecuted < numBatches) { + // Fill in the parameter values for this batch + Parameter paramValues[] = batchParamValues.get(numBatchesPrepared); + assert paramValues.length == batchParam.length; + System.arraycopy(paramValues, 0, batchParam, 0, paramValues.length); + + boolean hasExistingTypeDefinitions = preparedTypeDefinitions != null; + boolean hasNewTypeDefinitions = buildPreparedStrings(batchParam, false); + + // Get the encryption metadata for the first batch only. + if ((0 == numBatchesExecuted) && (Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection)) && (0 < batchParam.length) + && !isInternalEncryptionQuery && !encryptionMetadataIsRetrieved) { + getParameterEncryptionMetadata(batchParam); + + // fix an issue when inserting unicode into non-encrypted nchar column using setString() and AE is on on Connection + buildPreparedStrings(batchParam, true); + + // Save the crypto metadata retrieved for the first batch. We will re-use these for the rest of the batches. + for (Parameter aBatchParam : batchParam) { + cryptoMetaBatch.add(aBatchParam.cryptoMeta); + } } - } - // Update the crypto metadata for this batch. - if (0 < numBatchesExecuted) { - // cryptoMetaBatch will be empty for non-AE connections/statements. - for (int i = 0; i < cryptoMetaBatch.size(); i++) { - batchParam[i].cryptoMeta = cryptoMetaBatch.get(i); + // Update the crypto metadata for this batch. + if (0 < numBatchesExecuted) { + // cryptoMetaBatch will be empty for non-AE connections/statements. + for (int i = 0; i < cryptoMetaBatch.size(); i++) { + batchParam[i].cryptoMeta = cryptoMetaBatch.get(i); + } } - } - if (reuseCachedHandle(hasNewTypeDefinitions, false)) { - hasNewTypeDefinitions = false; - } + if (reuseCachedHandle(hasNewTypeDefinitions, false)) { + hasNewTypeDefinitions = false; + } - if (numBatchesExecuted < numBatchesPrepared) { - // assert null != tdsWriter; - tdsWriter.writeByte((byte) nBatchStatementDelimiter); - } - else { - resetForReexecute(); - tdsWriter = batchCommand.startRequest(TDS.PKT_RPC); - } + if (numBatchesExecuted < numBatchesPrepared) { + // assert null != tdsWriter; + tdsWriter.writeByte((byte) nBatchStatementDelimiter); + } + else { + resetForReexecute(); + tdsWriter = batchCommand.startRequest(TDS.PKT_RPC); + } - // If we have to (re)prepare the statement then we must execute it so - // that we get back a (new) prepared statement handle to use to - // execute additional batches. - // - // We must always prepare the statement the first time through. - // But we may also need to reprepare the statement if, for example, - // the size of a batch's string parameter values changes such - // that repreparation is necessary. - ++numBatchesPrepared; - - if (doPrepExec(tdsWriter, batchParam, hasNewTypeDefinitions, hasExistingTypeDefinitions) || numBatchesPrepared == numBatches) { - ensureExecuteResultsReader(batchCommand.startResponse(getIsResponseBufferingAdaptive())); - - while (numBatchesExecuted < numBatchesPrepared) { - // NOTE: - // When making changes to anything below, consider whether similar changes need - // to be made to Statement batch execution. - - startResults(); - - try { - // Get the first result from the batch. If there is no result for this batch - // then bail, leaving EXECUTE_FAILED in the current and remaining slots of - // the update count array. - if (!getNextResult()) - return; - - // If the result is a ResultSet (rather than an update count) then throw an - // exception for this result. The exception gets caught immediately below and - // translated into (or added to) a BatchUpdateException. - if (null != resultSet) { - SQLServerException.makeFromDriverError(connection, this, SQLServerException.getErrString("R_resultsetGeneratedForUpdate"), - null, false); - } - } - catch (SQLServerException e) { - // If the failure was severe enough to close the connection or roll back a - // manual transaction, then propagate the error up as a SQLServerException - // now, rather than continue with the batch. - if (connection.isSessionUnAvailable() || connection.rolledBackTransaction()) - throw e; - - // Otherwise, the connection is OK and the transaction is still intact, - // so just record the failure for the particular batch item. - updateCount = Statement.EXECUTE_FAILED; - if (null == batchCommand.batchException) - batchCommand.batchException = e; - - // throw the initial batchException - if (null != batchCommand.batchException) { - if (numBatchesExecuted < numBatchesPrepared) { - continue; + // If we have to (re)prepare the statement then we must execute it so + // that we get back a (new) prepared statement handle to use to + // execute additional batches. + // + // We must always prepare the statement the first time through. + // But we may also need to reprepare the statement if, for example, + // the size of a batch's string parameter values changes such + // that repreparation is necessary. + ++numBatchesPrepared; + + if (doPrepExec(tdsWriter, batchParam, hasNewTypeDefinitions, hasExistingTypeDefinitions) || numBatchesPrepared == numBatches) { + ensureExecuteResultsReader(batchCommand.startResponse(getIsResponseBufferingAdaptive())); + + while (numBatchesExecuted < numBatchesPrepared) { + // NOTE: + // When making changes to anything below, consider whether similar changes need + // to be made to Statement batch execution. + + startResults(); + + try { + // Get the first result from the batch. If there is no result for this batch + // then bail, leaving EXECUTE_FAILED in the current and remaining slots of + // the update count array. + if (!getNextResult()) + return; + + // If the result is a ResultSet (rather than an update count) then throw an + // exception for this result. The exception gets caught immediately below and + // translated into (or added to) a BatchUpdateException. + if (null != resultSet) { + SQLServerException.makeFromDriverError(connection, this, + SQLServerException.getErrString("R_resultsetGeneratedForUpdate"), null, false); } - else { + } + catch (SQLServerException e) { + // If the failure was severe enough to close the connection or roll back a + // manual transaction, then propagate the error up as a SQLServerException + // now, rather than continue with the batch. + if (connection.isSessionUnAvailable() || connection.rolledBackTransaction()) throw e; - } + + // Otherwise, the connection is OK and the transaction is still intact, + // so just record the failure for the particular batch item. + updateCount = Statement.EXECUTE_FAILED; + if (null == batchCommand.batchException) + batchCommand.batchException = e; } - } - // In batch execution, we have a special update count - // to indicate that no information was returned - batchCommand.updateCounts[numBatchesExecuted] = (-1 == updateCount) ? Statement.SUCCESS_NO_INFO : updateCount; - processBatch(); + // In batch execution, we have a special update count + // to indicate that no information was returned + batchCommand.updateCounts[numBatchesExecuted] = (-1 == updateCount) ? Statement.SUCCESS_NO_INFO : updateCount; + processBatch(); - numBatchesExecuted++; - } + numBatchesExecuted++; + } - // Only way to proceed with preparing the next set of batches is if - // we successfully executed the previously prepared set. - assert numBatchesExecuted == numBatchesPrepared; + // Only way to proceed with preparing the next set of batches is if + // we successfully executed the previously prepared set. + assert numBatchesExecuted == numBatchesPrepared; + } + } + } + catch (SQLServerException e) { + // throw the initial batchException + if (null != batchCommand.batchException) { + throw batchCommand.batchException; + } + else { + throw e; } } } From 1992eed7fe2ba9198a7e81daafa60829844a13bb Mon Sep 17 00:00:00 2001 From: Shawn Sun Date: Thu, 16 Nov 2017 16:10:02 -0800 Subject: [PATCH 65/68] re-enable metadata caching after context change --- .../sqlserver/jdbc/SQLServerPreparedStatement.java | 7 +++++++ .../com/microsoft/sqlserver/jdbc/SQLServerStatement.java | 1 + 2 files changed, 8 insertions(+) diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 438ac92ac..d18ebffb7 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -907,6 +907,13 @@ private void getParameterEncryptionMetadata(Parameter[] params) throws SQLServer private boolean reuseCachedHandle(boolean hasNewTypeDefinitions, boolean discardCurrentCacheItem) { if (definitionChanged || connection.contextChanged) { prepStmtHandle = -1; // so that hasPreparedStatementHandle() also returns false + + if (connection.contextChanged) { + connection.contextChanged = false; + connection.contextIsAlreadyChanged = false; + connection.clearCachedPreparedStatementHandle(); + } + return false; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java index 6c95bff86..9385fd165 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java @@ -805,6 +805,7 @@ final void setMaxRowsAndMaxFieldSize() throws SQLServerException { */ void checkIfContextChanged(String sql) { if (connection.contextIsAlreadyChanged) { + connection.contextChanged = true; return; } else if (sql.toUpperCase().contains("ANSI_NULLS") || sql.toUpperCase().contains("QUOTED_IDENTIFIER") || sql.toUpperCase().contains("USE") From 8d6d446a018840fa9253667561405827189a3a39 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 17 Nov 2017 09:36:57 -0800 Subject: [PATCH 66/68] Updated Changelog for 6.3.5 Release --- CHANGELOG.md | 8 ++++++++ README.md | 4 ++-- pom.xml | 2 +- .../java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java | 2 +- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe6a5717..95943e781 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## [6.3.5] Preview Release +### Added +- Added handle for Account Locked Exception 18486 during login in SQLServerConnection [#522](https://github.com/Microsoft/mssql-jdbc/pull/522) + +### Fixed Issues +- Fixed the issues with Prepared Statement Metadata Caching implementation [#543](https://github.com/Microsoft/mssql-jdbc/pull/543) +- Fixed issues with static logger member in abstract class 'SQLServerClobBase' [#537](https://github.com/Microsoft/mssql-jdbc/pull/537) + ## [6.3.4] Preview Release ### Added - Added new ThreadGroup creation to prevent IllegalThreadStateException if the underlying ThreadGroup has been destroyed. [#474](https://github.com/Microsoft/mssql-jdbc/pull/474) diff --git a/README.md b/README.md index 1edeca9e1..95907aa9d 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ To get the latest preview version of the driver, add the following to your POM f com.microsoft.sqlserver mssql-jdbc - 6.3.4.jre8-preview + 6.3.5.jre8-preview ``` @@ -120,7 +120,7 @@ Projects that require either of the two features need to explicitly declare the com.microsoft.sqlserver mssql-jdbc - 6.3.4.jre8-preview + 6.3.5.jre8-preview compile diff --git a/pom.xml b/pom.xml index a8ccbadda..676be09eb 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.5-SNAPSHOT.${jreVersion}-preview + 6.3.5.${jreVersion}-preview jar diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java index 2aa091ff0..67fdba21b 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java @@ -11,6 +11,6 @@ final class SQLJdbcVersion { static final int major = 6; static final int minor = 3; - static final int patch = 4; + static final int patch = 5; static final int build = 0; } From 91e7d8a12040511be05083e968cbfb5bdf362aac Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 17 Nov 2017 13:36:55 -0800 Subject: [PATCH 67/68] Update pom.xml Fixed minor issue that came during conflict resolution --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 45c492928..ed17d1125 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.5.${jreVersion}-preview6.3.5.${jreVersion}-preview jar Microsoft JDBC Driver for SQL Server From d69e01ba9dc42a4bbd39ec01fb234a7da2d6aaff Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Mon, 20 Nov 2017 10:38:49 -0800 Subject: [PATCH 68/68] Updating POM File for next preview snapshot --- pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 676be09eb..374aeadaf 100644 --- a/pom.xml +++ b/pom.xml @@ -4,8 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.5.${jreVersion}-preview - + 6.3.6-SNAPSHOT.${jreVersion}-preview jar Microsoft JDBC Driver for SQL Server