From 69fad3796c27bf7d1b382c4826e9edfc49915627 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Thu, 30 Aug 2018 14:09:04 -0700 Subject: [PATCH 01/15] tests cleanup --- .../bulkCopy/BulkCopyColumnMappingTest.java | 325 +++--- .../BulkCopyISQLServerBulkRecordTest.java | 9 +- .../bulkCopy/BulkCopyResultSetCursorTest.java | 13 + .../jdbc/connection/ConnectionDriverTest.java | 39 +- .../jdbc/connection/PoolingTest.java | 120 ++- .../RequestBoundaryMethodsTest.java | 46 +- .../jdbc/connection/SSLProtocolTest.java | 11 +- .../jdbc/connection/TimeoutTest.java | 235 +++-- .../jdbc/connection/WarningTest.java | 60 +- .../DatabaseMetaDataForeignKeyTest.java | 197 ++-- .../DatabaseMetaDataTest.java | 509 +++++---- .../jdbc/datatypes/TVPWithSqlVariantTest.java | 28 +- .../sqlserver/jdbc/fips/FipsTest.java | 54 +- .../BatchExecutionWithBulkCopyTest.java | 198 ++-- .../BatchExecutionWithNullTest.java | 17 +- .../preparedStatement/RegressionTest.java | 120 +-- .../jdbc/resultset/ResultSetTest.java | 20 +- .../sqlserver/jdbc/tvp/TVPAllTypes.java | 119 +-- .../sqlserver/jdbc/tvp/TVPIssuesTest.java | 72 +- .../sqlserver/jdbc/tvp/TVPNumericTest.java | 11 +- .../jdbc/tvp/TVPResultSetCursorTest.java | 246 ++--- .../sqlserver/jdbc/tvp/TVPSchemaTest.java | 56 +- .../sqlserver/jdbc/tvp/TVPTypesTest.java | 216 ++-- .../sqlserver/jdbc/unit/TestSavepoint.java | 88 +- .../sqlserver/jdbc/unit/UTF8SupportTest.java | 32 +- .../sqlserver/jdbc/unit/lobs/lobsTest.java | 457 ++++---- .../statement/BatchExecuteWithErrorsTest.java | 123 +-- .../unit/statement/BatchExecutionTest.java | 183 ++-- .../jdbc/unit/statement/BatchTriggerTest.java | 76 +- .../unit/statement/CallableMixedTest.java | 34 +- .../statement/NamedParamMultiPartTest.java | 31 +- .../unit/statement/PreparedStatementTest.java | 206 ++-- .../jdbc/unit/statement/RegressionTest.java | 285 +++-- .../jdbc/unit/statement/StatementTest.java | 988 +++++++++--------- .../jdbc/unit/statement/WrapperTest.java | 22 +- 35 files changed, 2667 insertions(+), 2579 deletions(-) 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 4f8a84c26..a76f87095 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -24,6 +24,7 @@ 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.sqlType.SqlType; import com.microsoft.sqlserver.testframework.util.ComparisonUtil; @@ -65,184 +66,214 @@ public void testNoExplicitCM() { BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable); + + // drop dest table + stmt.dropTable(destTable); } @Test @DisplayName("BulkCopy:test explicit column mapping") public void testExplicitCM() { - - // create dest table - DBTable destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with explicit column mapping - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - for (int i = 1; i <= destTable.totalColumns(); i++) { - int select = i % 4; - - switch (select) { - case 0: - bulkWrapper.setColumnMapping(i, i); - break; - - case 1: - bulkWrapper.setColumnMapping(i, destTable.getColumnName(i - 1)); - break; - - case 2: - bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), destTable.getColumnName(i - 1)); - break; - - case 3: - bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), i); - break; + DBTable destTable = null; + try { + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with explicit column mapping + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + for (int i = 1; i <= destTable.totalColumns(); i++) { + int select = i % 4; + + switch (select) { + case 0: + bulkWrapper.setColumnMapping(i, i); + break; + + case 1: + bulkWrapper.setColumnMapping(i, destTable.getColumnName(i - 1)); + break; + + case 2: + bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), destTable.getColumnName(i - 1)); + break; + + case 3: + bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), i); + break; + } + } + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable); + } finally { + // drop dest table + if (null != destTable) { + stmt.dropTable(destTable); } } - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable); } @Test @DisplayName("BulkCopy:test unicode column mapping") public void testUnicodeCM() { - - // create source unicode table - DBTable sourceTableUnicode = new DBTable(true, true); - stmt.createTable(sourceTableUnicode); - - // create destication unicode table with same schema as source - DBTable destTableUnicode = sourceTableUnicode.cloneSchema(); - stmt.createTable(destTableUnicode); - - // set up bulkCopy with explicit column mapping - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - for (int i = 1; i <= destTableUnicode.totalColumns(); i++) { - int select = i % 4; - - switch (select) { - case 0: - bulkWrapper.setColumnMapping(i, i); - break; - - case 1: - bulkWrapper.setColumnMapping(i, destTableUnicode.getColumnName(i - 1)); - break; - - case 2: - bulkWrapper.setColumnMapping(sourceTableUnicode.getColumnName(i - 1), - destTableUnicode.getColumnName(i - 1)); - break; - - case 3: - bulkWrapper.setColumnMapping(sourceTableUnicode.getColumnName(i - 1), i); - break; + DBTable sourceTableUnicode = null; + try { + // create source unicode table + sourceTableUnicode = new DBTable(true, true); + stmt.createTable(sourceTableUnicode); + + // create destination unicode table with same schema as source + DBTable destTableUnicode = sourceTableUnicode.cloneSchema(); + stmt.createTable(destTableUnicode); + + // set up bulkCopy with explicit column mapping + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + for (int i = 1; i <= destTableUnicode.totalColumns(); i++) { + int select = i % 4; + + switch (select) { + case 0: + bulkWrapper.setColumnMapping(i, i); + break; + + case 1: + bulkWrapper.setColumnMapping(i, destTableUnicode.getColumnName(i - 1)); + break; + + case 2: + bulkWrapper.setColumnMapping(sourceTableUnicode.getColumnName(i - 1), + destTableUnicode.getColumnName(i - 1)); + break; + + case 3: + bulkWrapper.setColumnMapping(sourceTableUnicode.getColumnName(i - 1), i); + break; + } + } + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTableUnicode, destTableUnicode); + } finally { + if (null != sourceTableUnicode) { + dropTable(sourceTableUnicode.getEscapedTableName()); } } - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTableUnicode, destTableUnicode); - dropTable(sourceTableUnicode.getEscapedTableName()); } @Test - @DisplayName("BulkCopy:test repetative column mapping") - public void testRepetativeCM() { - - // create source table - DBTable sourceTable1 = new DBTable(true); - stmt.createTable(sourceTable1); - stmt.populateTable(sourceTable1); - - // create destication table with same shcema as source - DBTable destTable = sourceTable1.cloneSchema(); - - // add 1 column to destination which will be duplicate of first source column - SqlType sqlType = sourceTable1.getSqlType(0); - destTable.addColumn(sqlType); - stmt.createTable(destTable); - - // set up bulkCopy with explicit column mapping - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - for (int i = 1; i <= sourceTable1.totalColumns(); i++) { - int select = i % 4; - - switch (select) { - case 0: - bulkWrapper.setColumnMapping(i, i); - break; - - case 1: - bulkWrapper.setColumnMapping(i, destTable.getColumnName(i - 1)); - break; - - case 2: - bulkWrapper.setColumnMapping(sourceTable1.getColumnName(i - 1), destTable.getColumnName(i - 1)); - break; - - case 3: - bulkWrapper.setColumnMapping(sourceTable1.getColumnName(i - 1), i); - break; + @DisplayName("BulkCopy:test repetitive column mapping") + public void testRepetitiveCM() { + DBTable sourceTable1 = null; + DBTable destTable = null; + try { + // create source table + sourceTable1 = new DBTable(true); + stmt.createTable(sourceTable1); + stmt.populateTable(sourceTable1); + + // create destination table with same schema as source + destTable = sourceTable1.cloneSchema(); + + // add 1 column to destination which will be duplicate of first source column + SqlType sqlType = sourceTable1.getSqlType(0); + destTable.addColumn(sqlType); + stmt.createTable(destTable); + + // set up bulkCopy with explicit column mapping + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + for (int i = 1; i <= sourceTable1.totalColumns(); i++) { + int select = i % 4; + + switch (select) { + case 0: + bulkWrapper.setColumnMapping(i, i); + break; + + case 1: + bulkWrapper.setColumnMapping(i, destTable.getColumnName(i - 1)); + break; + + case 2: + bulkWrapper.setColumnMapping(sourceTable1.getColumnName(i - 1), destTable.getColumnName(i - 1)); + break; + + case 3: + bulkWrapper.setColumnMapping(sourceTable1.getColumnName(i - 1), i); + break; + } } - } - // add column mapping for duplicate column in destination - bulkWrapper.setColumnMapping(1, 25); + // add column mapping for duplicate column in destination + bulkWrapper.setColumnMapping(1, 25); - // perform bulkCopy without validating results or dropping destination table - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable1, destTable, false, false, false); - try { - validateValuesRepetativeCM(con, sourceTable1, destTable); - } catch (SQLException e) { - MessageFormat form = new MessageFormat(TestResource.getResource("R_failedValidate")); - Object[] msgArgs = {sourceTable1.getTableName() + " and" + destTable.getTableName()}; + // perform bulkCopy without validating results or dropping destination table + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable1, destTable, false, false, false); + try { + validateValuesRepetitiveCM(con, sourceTable1, destTable); + } catch (SQLException e) { + MessageFormat form = new MessageFormat(TestResource.getResource("R_failedValidate")); + Object[] msgArgs = {sourceTable1.getTableName() + " and" + destTable.getTableName()}; - fail(form.format(msgArgs) + "\n" + destTable.getTableName() + "\n" + e.getMessage()); + fail(form.format(msgArgs) + "\n" + destTable.getTableName() + "\n" + e.getMessage()); + } + } finally { + if (null != sourceTable1) { + dropTable(sourceTable1.getEscapedTableName()); + } + if (null != destTable) { + dropTable(destTable.getEscapedTableName()); + } } - dropTable(sourceTable1.getEscapedTableName()); - dropTable(destTable.getEscapedTableName()); } @Test @DisplayName("BulkCopy:test implicit mismatched column mapping") public void testImplicitMismatchCM() { - - // create non unicode dest table with different schema from source table - DBTable destTable = new DBTable(true, false, true); - stmt.createTable(destTable); - - // set up bulkCopy with explicit column mapping - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - for (int i = 1; i <= destTable.totalColumns(); i++) { - int select = i % 4; - - switch (select) { - case 0: - bulkWrapper.setColumnMapping(i, i); - break; - - case 1: - bulkWrapper.setColumnMapping(i, destTable.getColumnName(i - 1)); - break; - - case 2: - bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), destTable.getColumnName(i - 1)); - break; - - case 3: - bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), i); - break; + DBTable destTable = null; + try { + // create non unicode dest table with different schema from source table + destTable = new DBTable(true, false, true); + stmt.createTable(destTable); + + // set up bulkCopy with explicit column mapping + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + for (int i = 1; i <= destTable.totalColumns(); i++) { + int select = i % 4; + + switch (select) { + case 0: + bulkWrapper.setColumnMapping(i, i); + break; + + case 1: + bulkWrapper.setColumnMapping(i, destTable.getColumnName(i - 1)); + break; + + case 2: + bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), destTable.getColumnName(i - 1)); + break; + + case 3: + bulkWrapper.setColumnMapping(sourceTable.getColumnName(i - 1), i); + break; + } + } + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + } finally { + if (null != destTable) { + stmt.dropTable(destTable); } } - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); } @Test @DisplayName("BulkCopy:test invalid column mapping") public void testInvalidCM() { - + DBTable destTable = null; + try { // create dest table - DBTable destTable = sourceTable.cloneSchema(); + destTable = sourceTable.cloneSchema(); stmt.createTable(destTable); // set up bulkCopy with wrong column names @@ -320,7 +351,11 @@ public void testInvalidCM() { bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); bulkWrapper.setColumnMapping(Integer.MIN_VALUE, Integer.MAX_VALUE); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - + } finally { + if (null != destTable) { + stmt.dropTable(destTable); + } + } } /** @@ -332,7 +367,7 @@ public void testInvalidCM() { * @param destinationTable * @throws SQLException */ - private void validateValuesRepetativeCM(DBConnection con, DBTable sourceTable, + private void validateValuesRepetitiveCM(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { try (DBStatement srcStmt = con.createStatement(); DBStatement dstStmt = con.createStatement(); DBResultSet srcResultSet = srcStmt 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 055430b30..ee922f746 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java @@ -37,14 +37,21 @@ public class BulkCopyISQLServerBulkRecordTest extends AbstractTest { @Test public void testISQLServerBulkRecord() throws SQLException { + DBTable dstTable = null; try (DBConnection con = new DBConnection(connectionString); DBStatement stmt = con.createStatement()) { - DBTable dstTable = new DBTable(true); + 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); + } finally { + if (null != dstTable) { + try (DBConnection con = new DBConnection(connectionString); DBStatement stmt = con.createStatement()) { + stmt.dropTable(dstTable); + } + } } } 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 ad6a497e3..2504fa0a4 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; @@ -214,4 +215,16 @@ private static void createTables(Statement stmt) throws SQLException { + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } + + /** + * drops tables + * + * @throws SQLException + */ + @AfterAll + public static void terminate() throws SQLException { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + dropTables(stmt); + } + } } 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 20e50feb6..61c5cdfcc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -6,6 +6,7 @@ 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 static org.junit.jupiter.api.Assumptions.assumeTrue; import java.sql.Connection; @@ -53,7 +54,7 @@ public class ConnectionDriverTest extends AbstractTest { String randomServer = RandomUtil.getIdentifier("Server"); /** - * test SSL properties + * test connection properties * * @throws SQLException */ @@ -92,7 +93,7 @@ public void testConnectionDriver() throws SQLException { } /** - * test SSL properties with SQLServerDataSource + * test connection properties with SQLServerDataSource */ @Test public void testDataSource() { @@ -229,15 +230,17 @@ public void testConnectionClosed() throws SQLException { SQLServerDataSource mds = new SQLServerDataSource(); mds.setURL(connectionString); Connection con = mds.getConnection(); - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - - boolean exceptionThrown = false; - try { - stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + boolean exceptionThrown = false; + try { + stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + } catch (Exception e) { + exceptionThrown = true; + } + assertTrue(exceptionThrown, TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { - exceptionThrown = true; + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } - assertTrue(exceptionThrown, TestResource.getResource("R_expectedExceptionNotThrown")); // check to make sure that connection is closed. assertTrue(con.isClosed(), TestResource.getResource("R_connectionIsNotClosed")); @@ -302,15 +305,15 @@ public void testDeadConnection() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), TestResource.getResource("R_skipAzure")); + String tableName = null; try (SQLServerConnection conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";responseBuffering=adaptive")) { + .getConnection(connectionString + ";responseBuffering=adaptive"); + Statement stmt = conn.createStatement()) { - Statement stmt = null; - String tableName = RandomUtil.getIdentifier("Table"); + 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 + ")"); @@ -322,10 +325,16 @@ public void testDeadConnection() throws SQLException { } catch (SQLException e) { assertEquals(e.getMessage(), TestResource.getResource("R_connectionReset"), TestResource.getResource("R_unknownException")); - } finally { - DriverManager.getConnection(connectionString).createStatement().execute("drop table " + tableName); } assertEquals(conn.isValid(5), false, TestResource.getResource("R_deadConnection")); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + try (SQLServerConnection conn = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";responseBuffering=adaptive"); + Statement stmt = conn.createStatement()) { + stmt.execute("drop table " + tableName); + } } } 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 ef89129f9..fbfc0eb88 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -6,6 +6,7 @@ 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 static org.junit.jupiter.api.Assumptions.assumeTrue; import java.lang.management.ManagementFactory; @@ -58,16 +59,16 @@ public void testPooling() throws SQLException { XADataSource1.setDatabaseName("tempdb"); PooledConnection pc = XADataSource1.getPooledConnection(); - try (Connection conn = pc.getConnection()) { + try (Connection conn = pc.getConnection(); Statement stmt = conn.createStatement()) { // create table in tempdb database - conn.createStatement().execute("create table [" + tempTableName + "] (myid int)"); - conn.createStatement().execute("insert into [" + tempTableName + "] values (1)"); + stmt.execute("create table [" + tempTableName + "] (myid int)"); + stmt.execute("insert into [" + tempTableName + "] values (1)"); } boolean tempTableFileRemoved = false; - try (Connection conn = pc.getConnection()) { - conn.createStatement().executeQuery("select * from [" + tempTableName + "]"); + try (Connection conn = pc.getConnection(); Statement stmt = conn.createStatement()) { + stmt.executeQuery("select * from [" + tempTableName + "]"); } catch (SQLException e) { // make sure the temporary table is not found. if (e.getMessage().startsWith(TestResource.getResource("R_invalidObjectName"))) { @@ -81,15 +82,32 @@ public void testPooling() throws SQLException { public void testConnectionPoolReget() throws SQLException { SQLServerXADataSource ds = new SQLServerXADataSource(); ds.setURL(connectionString); - - PooledConnection pc = ds.getPooledConnection(); - Connection con = pc.getConnection(); - - // now reget a connection - Connection con2 = pc.getConnection(); - - // assert that the first connection is closed. - assertTrue(con.isClosed(), TestResource.getResource("R_firstConnectionNotClosed")); + PooledConnection pc = null; + try { + pc = ds.getPooledConnection(); + Connection con = null; + Connection con2 = null; + try { + con = pc.getConnection(); + + // now re-get a connection + con2 = pc.getConnection(); + + // assert that the first connection is closed. + assertTrue(con.isClosed(), TestResource.getResource("R_firstConnectionNotClosed")); + } finally { + if (null != con) { + con.close(); + } + if (null != con2) { + con2.close(); + } + } + } finally { + if (null != pc) { + pc.close(); + } + } } @Test @@ -111,8 +129,14 @@ public void testConnectionPoolConnFunctions() throws SQLException { statement.execute(sql1); statement.execute(sql2); con.clearWarnings(); + + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != pc) { + pc.close(); + } } - pc.close(); } @Test @@ -121,32 +145,45 @@ public void testConnectionPoolClose() throws SQLException { ds.setURL(connectionString); PooledConnection pc = ds.getPooledConnection(); - Connection con = pc.getConnection(); + try (Connection con = pc.getConnection()) { + pc.close(); - pc.close(); - // assert that the first connection is closed. - assertTrue(con.isClosed(), TestResource.getResource("R_connectionNotClosedWithPoolClose")); + // assert that the first connection is closed. + assertTrue(con.isClosed(), TestResource.getResource("R_connectionNotClosedWithPoolClose")); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != pc) { + pc.close(); + } + } } @Test public void testConnectionPoolClientConnectionId() throws SQLException { SQLServerXADataSource ds = new SQLServerXADataSource(); ds.setURL(connectionString); + PooledConnection pc = null; + try { + pc = ds.getPooledConnection(); + ISQLServerConnection con = (ISQLServerConnection) pc.getConnection(); - PooledConnection pc = ds.getPooledConnection(); - ISQLServerConnection con = (ISQLServerConnection) pc.getConnection(); - - UUID Id1 = con.getClientConnectionId(); - assertTrue(Id1 != null, TestResource.getResource("R_connectionNotClosedWithPoolClose")); - con.close(); + UUID Id1 = con.getClientConnectionId(); + assertTrue(Id1 != null, TestResource.getResource("R_connectionNotClosedWithPoolClose")); + con.close(); - // now reget the connection - ISQLServerConnection con2 = (ISQLServerConnection) pc.getConnection(); + // now reget the connection + ISQLServerConnection con2 = (ISQLServerConnection) pc.getConnection(); - UUID Id2 = con2.getClientConnectionId(); - con2.close(); + UUID Id2 = con2.getClientConnectionId(); + con2.close(); - assertEquals(Id1, Id2, TestResource.getResource("R_idFromPoolNotSame")); + assertEquals(Id1, Id2, TestResource.getResource("R_idFromPoolNotSame")); + } finally { + if (null != pc) { + pc.close(); + } + } } /** @@ -191,15 +228,8 @@ public void testApacheDBCP() throws SQLException { * @throws SQLException */ private static void connect(DataSource ds) throws SQLException { - Connection con = null; - PreparedStatement pst = null; - ResultSet rs = null; - - try { - con = ds.getConnection(); - pst = con.prepareStatement("SELECT SUSER_SNAME()"); - pst.setQueryTimeout(5); - rs = pst.executeQuery(); + try (Connection con = ds.getConnection(); PreparedStatement pst = con.prepareStatement("SELECT SUSER_SNAME()"); + ResultSet rs = pst.executeQuery()) { // TODO : we are commenting this out due to AppVeyor failures. Will investigate later. // assertTrue(countTimeoutThreads() >= 1, "Timeout timer is missing."); @@ -207,18 +237,6 @@ private static void connect(DataSource ds) throws SQLException { while (rs.next()) { rs.getString(1); } - } finally { - if (rs != null) { - rs.close(); - } - - if (pst != null) { - pst.close(); - } - - if (con != null) { - con.close(); - } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java index 0a2f73e12..c6ea0df75 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -72,10 +72,10 @@ public void testModifiableConnectionProperties() throws SQLException { String sCatalog2 = RandomUtil.getIdentifier("RequestBoundaryDatabase"); boolean useBulkCopyForBatchInsert2 = false; - try (SQLServerConnection con = connect()) { + try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { if (Utils.isJDBC43OrGreater(con)) { // Second database - con.createStatement().executeUpdate("CREATE DATABASE [" + sCatalog2 + "]"); + stmt.executeUpdate("CREATE DATABASE [" + sCatalog2 + "]"); // First set of values. setConnectionFields(con, autoCommitMode1, transactionIsolationLevel1, networkTimeout1, holdability1, @@ -130,7 +130,10 @@ public void testModifiableConnectionProperties() throws SQLException { useBulkCopyForBatchInsert2); // drop the database con.setCatalog("master"); - Utils.dropDatabaseIfExists(sCatalog2, con.createStatement()); + } + } finally { + try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { + Utils.dropDatabaseIfExists(sCatalog2, stmt); } } } @@ -174,7 +177,7 @@ public void testOpenTransactions() throws SQLException { ResultSet rs = null; String tableName = null; - try (SQLServerConnection con = connect(); Statement stmt = con.createStatement();) { + try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { if (Utils.isJDBC43OrGreater(con)) { tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundaryTable")); Utils.dropTableIfExists(tableName, stmt); @@ -188,7 +191,18 @@ public void testOpenTransactions() throws SQLException { rs = con.createStatement().executeQuery("SELECT * from " + tableName); assertTrue(!rs.isBeforeFirst(), "Should not have returned a result set."); - Utils.dropTableIfExists(tableName, con.createStatement()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (null != rs) { + rs.close(); + } + + if (null != tableName) { + try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { + Utils.dropTableIfExists(tableName, stmt); + } } } } @@ -240,7 +254,6 @@ public void testStatements() throws SQLException { rs1 = stmt1.executeQuery("SELECT * FROM " + tableName); rs1.next(); assertEquals(2, rs1.getInt(1)); - Utils.dropTableIfExists(tableName, stmt); cs = con.prepareCall("{call sp_server_info}"); cs.execute(); @@ -265,6 +278,9 @@ public void testStatements() throws SQLException { if (null != cs) { cs.close(); } + try (SQLServerConnection con = connect(); Statement st = con.createStatement()) { + Utils.dropTableIfExists(tableName, st); + } } } @@ -303,10 +319,11 @@ public void run() { public void run() { try { sharedVariables.stmt = sharedVariables.con.createStatement(); - ResultSet rs = sharedVariables.stmt.executeQuery("SELECT 1"); - rs.next(); - assertEquals(1, rs.getInt(1)); - latch.countDown(); + try (ResultSet rs = sharedVariables.stmt.executeQuery("SELECT 1")) { + rs.next(); + assertEquals(1, rs.getInt(1)); + latch.countDown(); + } } catch (SQLException e) { e.printStackTrace(); Thread.currentThread().interrupt(); @@ -318,10 +335,11 @@ public void run() { public void run() { try { sharedVariables.pstmt = sharedVariables.con.prepareStatement("SELECT 1"); - ResultSet rs = sharedVariables.pstmt.executeQuery(); - rs.next(); - assertEquals(1, rs.getInt(1)); - latch.countDown(); + try (ResultSet rs = sharedVariables.pstmt.executeQuery()) { + rs.next(); + assertEquals(1, rs.getInt(1)); + latch.countDown(); + } } catch (SQLException e) { e.printStackTrace(); Thread.currentThread().interrupt(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java index cdab7c139..5922ddbe5 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java @@ -30,9 +30,6 @@ @RunWith(JUnitPlatform.class) public class SSLProtocolTest extends AbstractTest { - Connection con = null; - Statement stmt = null; - /** * Connect with supported protocol * @@ -41,8 +38,7 @@ public class SSLProtocolTest extends AbstractTest { */ public void testWithSupportedProtocols(String sslProtocol) throws Exception { String url = connectionString + ";sslProtocol=" + sslProtocol; - try { - con = DriverManager.getConnection(url); + try (Connection con = DriverManager.getConnection(url)) { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(!StringUtils.isEmpty(dbmd.getDatabaseProductName())); @@ -61,9 +57,8 @@ public void testWithSupportedProtocols(String sslProtocol) throws Exception { * @throws Exception */ public void testWithUnSupportedProtocols(String sslProtocol) throws Exception { - try { - String url = connectionString + ";sslProtocol=" + sslProtocol; - con = DriverManager.getConnection(url); + String url = connectionString + ";sslProtocol=" + sslProtocol; + try (Connection con = DriverManager.getConnection(url)) { assertFalse(true, TestResource.getResource("R_protocolVersion")); } catch (SQLServerException e) { assertTrue(true, TestResource.getResource("R_shouldThrowException")); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java index 53d7f564b..28613d790 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java @@ -8,6 +8,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.sql.Connection; +import java.sql.Statement; import java.sql.DriverManager; import java.sql.SQLException; @@ -35,14 +37,17 @@ public class TimeoutTest extends AbstractTest { public void testDefaultLoginTimeout() { long timerStart = 0; long timerEnd = 0; - try { - timerStart = System.currentTimeMillis(); - // Try a non existing server and see if the default timeout is 15 seconds - DriverManager.getConnection("jdbc:sqlserver://" + randomServer + ";user=sa;password=pwd;"); - } catch (Exception e) { + + timerStart = System.currentTimeMillis(); + // Try a non existing server and see if the default timeout is 15 seconds + try (Connection con = DriverManager.getConnection("jdbc:sqlserver://" + randomServer + ";user=sa;password=pwd;")) { + + } + catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_tcpipConnectionToHost"))); timerEnd = System.currentTimeMillis(); } + assertTrue(0 != timerEnd, TestResource.getResource("R_shouldNotConnect")); long timeDiff = timerEnd - timerStart; @@ -53,12 +58,12 @@ public void testDefaultLoginTimeout() { public void testFailoverInstanceResolution() throws SQLException { long timerStart = 0; long timerEnd = 0; - try { - timerStart = System.currentTimeMillis(); - // Try a non existing server and see if the default timeout is 15 seconds - DriverManager.getConnection("jdbc:sqlserver://" + randomServer - + ";databaseName=FailoverDB_abc;failoverPartner=" + randomServer + "\\foo;user=sa;password=pwd;"); - } catch (Exception e) { + + timerStart = System.currentTimeMillis(); + // Try a non existing server and see if the default timeout is 15 seconds + try (Connection con = DriverManager + .getConnection("jdbc:sqlserver://" + randomServer + ";databaseName=FailoverDB_abc;failoverPartner=" + + randomServer + "\\foo;user=sa;password=pwd;")) {} catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_tcpipConnectionToHost"))); timerEnd = System.currentTimeMillis(); } @@ -72,13 +77,11 @@ public void testFailoverInstanceResolution() throws SQLException { public void testFOInstanceResolution2() throws SQLException { long timerStart = 0; long timerEnd = 0; - try { - timerStart = System.currentTimeMillis(); - // Try a non existing server and see if the default timeout is 15 secs at least - DriverManager.getConnection( - "jdbc:sqlserver://" + randomServer + "\\fooggg;databaseName=FailoverDB;failoverPartner=" - + randomServer + "\\foo;user=sa;password=pwd;"); - } catch (Exception e) { + + timerStart = System.currentTimeMillis(); + try (Connection con = DriverManager + .getConnection("jdbc:sqlserver://" + randomServer + "\\fooggg;databaseName=FailoverDB;failoverPartner=" + + randomServer + "\\foo;user=sa;password=pwd;")) {} catch (Exception e) { timerEnd = System.currentTimeMillis(); } assertTrue(0 != timerEnd, TestResource.getResource("R_shouldNotConnect")); @@ -94,30 +97,40 @@ public void testFOInstanceResolution2() throws SQLException { */ @Test public void testQueryTimeout() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerConnection conn = null; + try { + conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - dropWaitForDelayProcedure(conn); - createWaitForDelayPreocedure(conn); + dropWaitForDelayProcedure(conn); + createWaitForDelayPreocedure(conn); - conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";"); + conn = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";"); - try { - conn.createStatement().execute("exec " + waitForDelaySPName); - throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (Exception e) { - if (!(e instanceof java.sql.SQLTimeoutException)) { - throw e; + try (Statement stmt = conn.createStatement()) { + stmt.execute("exec " + waitForDelaySPName); + throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (Exception e) { + if (!(e instanceof java.sql.SQLTimeoutException)) { + throw e; + } + assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), + TestResource.getResource("R_invalidExceptionMessage")); + } + + try (Statement stmt = conn.createStatement()) { + stmt.execute("SELECT @@version"); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } - assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), - TestResource.getResource("R_invalidExceptionMessage")); - } - try { - conn.createStatement().execute("SELECT @@version"); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != conn) { + conn.close(); + } } - } + } /** * Tests sanity of connection property. @@ -126,29 +139,38 @@ public void testQueryTimeout() throws Exception { */ @Test public void testCancelQueryTimeout() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerConnection conn = null; - dropWaitForDelayProcedure(conn); - createWaitForDelayPreocedure(conn); + try { + conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";queryTimeout=" - + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + ";"); + dropWaitForDelayProcedure(conn); + createWaitForDelayPreocedure(conn); - try { - SQLServerStatement statement = (SQLServerStatement) conn.createStatement(); - statement.execute("exec " + waitForDelaySPName); - throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (Exception e) { - if (!(e instanceof java.sql.SQLTimeoutException)) { - throw e; + conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";queryTimeout=" + + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + ";"); + + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + stmt.execute("exec " + waitForDelaySPName); + throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (Exception e) { + if (!(e instanceof java.sql.SQLTimeoutException)) { + throw e; + } + assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), + TestResource.getResource("R_invalidExceptionMessage")); + } + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + stmt.execute("SELECT @@version"); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } - assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), - TestResource.getResource("R_invalidExceptionMessage")); - } - try { - conn.createStatement().execute("SELECT @@version"); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != conn) { + conn.close(); + } } } @@ -159,30 +181,39 @@ public void testCancelQueryTimeout() throws Exception { */ @Test public void testCancelQueryTimeoutOnStatement() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerConnection conn = null; - dropWaitForDelayProcedure(conn); - createWaitForDelayPreocedure(conn); + try { + conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";"); + dropWaitForDelayProcedure(conn); + createWaitForDelayPreocedure(conn); - try { - SQLServerStatement statement = (SQLServerStatement) conn.createStatement(); - statement.setQueryTimeout(waitForDelaySeconds / 2); - statement.setCancelQueryTimeout(waitForDelaySeconds); - statement.execute("exec " + waitForDelaySPName); - throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (Exception e) { - if (!(e instanceof java.sql.SQLTimeoutException)) { - throw e; + conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";"); + + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + stmt.setQueryTimeout(waitForDelaySeconds / 2); + stmt.setCancelQueryTimeout(waitForDelaySeconds); + stmt.execute("exec " + waitForDelaySPName); + throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (Exception e) { + if (!(e instanceof java.sql.SQLTimeoutException)) { + throw e; + } + assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), + TestResource.getResource("R_invalidExceptionMessage")); + } + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + stmt.execute("SELECT @@version"); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } - assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), - TestResource.getResource("R_invalidExceptionMessage")); - } - try { - conn.createStatement().execute("SELECT @@version"); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != conn) { + conn.close(); + } } } @@ -193,39 +224,59 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { */ @Test public void testSocketTimeout() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerConnection conn = null; + + try { - dropWaitForDelayProcedure(conn); - createWaitForDelayPreocedure(conn); + conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); + dropWaitForDelayProcedure(conn); + createWaitForDelayPreocedure(conn); - try { - conn.createStatement().execute("exec " + waitForDelaySPName); - throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + conn = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); + + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + stmt.execute("exec " + waitForDelaySPName); + throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (Exception e) { + if (!(e instanceof SQLException)) { + throw e; + } + assertEquals(e.getMessage(), TestResource.getResource("R_readTimedOut"), + TestResource.getResource("R_invalidExceptionMessage")); + } + try { + conn.createStatement().execute("SELECT @@version"); + } catch (SQLException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_connectionIsClosed"), + TestResource.getResource("R_invalidExceptionMessage")); + } } catch (Exception e) { - if (!(e instanceof SQLException)) { - throw e; + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != conn) { + conn.close(); } - assertEquals(e.getMessage(), TestResource.getResource("R_readTimedOut"), - TestResource.getResource("R_invalidExceptionMessage")); - } - try { - conn.createStatement().execute("SELECT @@version"); - } catch (SQLException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_connectionIsClosed"), - TestResource.getResource("R_invalidExceptionMessage")); } } private void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLException { - Utils.dropProcedureIfExists(waitForDelaySPName, conn.createStatement()); + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + Utils.dropProcedureIfExists(waitForDelaySPName, stmt); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } private void createWaitForDelayPreocedure(SQLServerConnection conn) throws SQLException { - String sql = "CREATE PROCEDURE " + waitForDelaySPName + " AS" + " BEGIN" + " WAITFOR DELAY '00:00:" - + waitForDelaySeconds + "';" + " END"; - conn.createStatement().execute(sql); + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + + String sql = "CREATE PROCEDURE " + waitForDelaySPName + " AS" + " BEGIN" + " WAITFOR DELAY '00:00:" + + waitForDelaySeconds + "';" + " END"; + stmt.execute(sql); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } } 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 45d15dc20..e9693b8c0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java @@ -6,6 +6,7 @@ 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.sql.DriverManager; import java.sql.SQLException; @@ -27,39 +28,42 @@ public class WarningTest extends AbstractTest { @Test public void testWarnings() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - Properties info = conn.getClientInfo(); - conn.setClientInfo(info); - SQLWarning warn = conn.getWarnings(); - assertEquals(null, warn, "Warnings found."); + Properties info = conn.getClientInfo(); + conn.setClientInfo(info); + SQLWarning warn = conn.getWarnings(); + assertEquals(null, warn, "Warnings found."); - Properties info2 = new Properties(); - String[] infoArray = {"prp1", "prp2", "prp3", "prp4", "prp5"}; - for (int i = 0; i < 5; i++) { - info2.put(infoArray[i], ""); - } - 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; + Properties info2 = new Properties(); + String[] infoArray = {"prp1", "prp2", "prp3", "prp4", "prp5"}; + for (int i = 0; i < 5; i++) { + info2.put(infoArray[i], ""); + } + 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, TestResource.getResource("R_warningsNotFound") + ": " + warn.toString()); + warn = warn.getNextWarning(); + found = false; } - assertTrue(found, TestResource.getResource("R_warningsNotFound") + ": " + warn.toString()); + conn.clearWarnings(); + + conn.setClientInfo("prop7", ""); + warn = conn.getWarnings(); + assertTrue(warn.toString().contains("prop7"), TestResource.getResource("R_warningsNotFound")); warn = warn.getNextWarning(); - found = false; + assertEquals(null, warn, TestResource.getResource("R_warningsFound")); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } - conn.clearWarnings(); - - conn.setClientInfo("prop7", ""); - warn = conn.getWarnings(); - assertTrue(warn.toString().contains("prop7"), TestResource.getResource("R_warningsNotFound")); - warn = warn.getNextWarning(); - assertEquals(null, warn, TestResource.getResource("R_warningsFound")); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java index 8c38b10d8..600757bb9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java @@ -33,7 +33,6 @@ @RunWith(JUnitPlatform.class) public class DatabaseMetaDataForeignKeyTest extends AbstractTest { private static SQLServerConnection conn = null; - private static SQLServerStatement stmt = null; private static String table1 = "DatabaseMetaDataForeignKeyTest_table_1"; private static String table2 = "DatabaseMetaDataForeignKeyTest_table_2"; @@ -46,50 +45,46 @@ public class DatabaseMetaDataForeignKeyTest extends AbstractTest { @BeforeAll public static void setupVariation() throws SQLException { - conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) conn.createStatement(); - - catalog = conn.getCatalog(); - schema = conn.getSchema(); - - connection.createStatement() - .executeUpdate("if object_id('" + table1 + "','U') is not null drop table " + table1); - - connection.createStatement() - .executeUpdate("if object_id('" + table2 + "','U') is not null drop table " + table2); - stmt.execute("Create table " + table2 + " (c21 int NOT NULL PRIMARY KEY)"); - - connection.createStatement() - .executeUpdate("if object_id('" + table3 + "','U') is not null drop table " + table3); - stmt.execute("Create table " + table3 + " (c31 int NOT NULL PRIMARY KEY)"); - - connection.createStatement() - .executeUpdate("if object_id('" + table4 + "','U') is not null drop table " + table4); - stmt.execute("Create table " + table4 + " (c41 int NOT NULL PRIMARY KEY)"); - - connection.createStatement() - .executeUpdate("if object_id('" + table5 + "','U') is not null drop table " + table5); - stmt.execute("Create table " + table5 + " (c51 int NOT NULL PRIMARY KEY)"); - - connection.createStatement() - .executeUpdate("if object_id('" + table1 + "','U') is not null drop table " + table1); - stmt.execute("Create table " + table1 + " (c11 int primary key," + " c12 int FOREIGN KEY REFERENCES " + table2 - + "(c21) ON DELETE no action ON UPDATE set default," + " c13 int FOREIGN KEY REFERENCES " + table3 - + "(c31) ON DELETE cascade ON UPDATE set null," + " c14 int FOREIGN KEY REFERENCES " + table4 - + "(c41) ON DELETE set null ON UPDATE cascade," + " c15 int FOREIGN KEY REFERENCES " + table5 - + "(c51) ON DELETE set default ON UPDATE no action," + ")"); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + catalog = conn.getCatalog(); + schema = conn.getSchema(); + + stmt.executeUpdate("if object_id('" + table1 + "','U') is not null drop table " + table1); + + stmt.executeUpdate("if object_id('" + table2 + "','U') is not null drop table " + table2); + stmt.execute("Create table " + table2 + " (c21 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + table3 + "','U') is not null drop table " + table3); + stmt.execute("Create table " + table3 + " (c31 int NOT NULL PRIMARY KEY)"); + stmt.executeUpdate("if object_id('" + table4 + "','U') is not null drop table " + table4); + stmt.execute("Create table " + table4 + " (c41 int NOT NULL PRIMARY KEY)"); + stmt.executeUpdate("if object_id('" + table5 + "','U') is not null drop table " + table5); + stmt.execute("Create table " + table5 + " (c51 int NOT NULL PRIMARY KEY)"); + stmt.executeUpdate("if object_id('" + table1 + "','U') is not null drop table " + table1); + stmt.execute("Create table " + table1 + " (c11 int primary key," + " c12 int FOREIGN KEY REFERENCES " + + table2 + "(c21) ON DELETE no action ON UPDATE set default," + " c13 int FOREIGN KEY REFERENCES " + + table3 + "(c31) ON DELETE cascade ON UPDATE set null," + " c14 int FOREIGN KEY REFERENCES " + + table4 + "(c41) ON DELETE set null ON UPDATE cascade," + " c15 int FOREIGN KEY REFERENCES " + + table5 + "(c51) ON DELETE set default ON UPDATE no action," + ")"); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } - + @AfterAll public static void terminateVariation() throws SQLException { - conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = (SQLServerStatement) conn.createStatement(); - - Utils.dropTableIfExists(table1, stmt); - Utils.dropTableIfExists(table2, stmt); - Utils.dropTableIfExists(table3, stmt); - Utils.dropTableIfExists(table4, stmt); - Utils.dropTableIfExists(table5, stmt); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + + Utils.dropTableIfExists(table1, stmt); + Utils.dropTableIfExists(table2, stmt); + Utils.dropTableIfExists(table3, stmt); + Utils.dropTableIfExists(table4, stmt); + Utils.dropTableIfExists(table5, stmt); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } /** @@ -100,22 +95,40 @@ public static void terminateVariation() throws SQLException { */ @Test public void testGetImportedKeys() throws SQLException { - SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) connection.getMetaData(); - - SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getImportedKeys(null, null, table1); - validateGetImportedKeysResults(rs1); - - SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getImportedKeys(catalog, schema, table1); - validateGetImportedKeysResults(rs2); - - SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getImportedKeys(catalog, "", table1); - validateGetImportedKeysResults(rs3); - - try { - dmd.getImportedKeys("", schema, table1); - fail(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + SQLServerResultSet rs1 = null; + SQLServerResultSet rs2 = null; + SQLServerResultSet rs3 = null; + + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) conn.getMetaData(); + + rs1 = (SQLServerResultSet) dmd.getImportedKeys(null, null, table1); + validateGetImportedKeysResults(rs1); + + rs2 = (SQLServerResultSet) dmd.getImportedKeys(catalog, schema, table1); + validateGetImportedKeysResults(rs2); + + rs3 = (SQLServerResultSet) dmd.getImportedKeys(catalog, "", table1); + validateGetImportedKeysResults(rs3); + + try { + dmd.getImportedKeys("", schema, table1); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != rs1) { + rs1.close(); + } + if (null != rs2) { + rs2.close(); + } + if (null != rs3) { + rs3.close(); + } } } @@ -160,31 +173,49 @@ public void testGetExportedKeys() throws SQLException { int[][] values = { // expected UPDATE_RULE, expected DELETE_RULE {4, 3}, {2, 0}, {0, 2}, {3, 4}}; - - SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) connection.getMetaData(); - - for (int i = 0; i < tableNames.length; i++) { - String pkTable = tableNames[i]; - SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getExportedKeys(null, null, pkTable); - rs1.next(); - assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs1.getInt("DELETE_RULE")); - - SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getExportedKeys(catalog, schema, pkTable); - rs2.next(); - assertEquals(values[i][0], rs2.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs2.getInt("DELETE_RULE")); - - SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getExportedKeys(catalog, "", pkTable); - rs3.next(); - assertEquals(values[i][0], rs3.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs3.getInt("DELETE_RULE")); - - try { - dmd.getExportedKeys("", schema, pkTable); - fail(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + SQLServerResultSet rs1 = null; + SQLServerResultSet rs2 = null; + SQLServerResultSet rs3 = null; + + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + + SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) conn.getMetaData(); + + for (int i = 0; i < tableNames.length; i++) { + String pkTable = tableNames[i]; + rs1 = (SQLServerResultSet) dmd.getExportedKeys(null, null, pkTable); + rs1.next(); + assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs1.getInt("DELETE_RULE")); + + rs2 = (SQLServerResultSet) dmd.getExportedKeys(catalog, schema, pkTable); + rs2.next(); + assertEquals(values[i][0], rs2.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs2.getInt("DELETE_RULE")); + + rs3 = (SQLServerResultSet) dmd.getExportedKeys(catalog, "", pkTable); + rs3.next(); + assertEquals(values[i][0], rs3.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs3.getInt("DELETE_RULE")); + + try { + dmd.getExportedKeys("", schema, pkTable); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + } + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != rs1) { + rs1.close(); + } + if (null != rs2) { + rs2.close(); + } + if (null != rs3) { + rs3.close(); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index 95f0c2799..e5ee1e258 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -10,6 +10,7 @@ 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 static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.BufferedInputStream; @@ -32,7 +33,9 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData; +import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.StringUtils; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -86,29 +89,33 @@ public void testDriverVersion() throws SQLException, IOException { Attributes attributes = manifest.getMainAttributes(); String buildVersion = attributes.getValue("Bundle-Version"); - DatabaseMetaData dbmData = connection.getMetaData(); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - String driverVersion = dbmData.getDriverVersion(); + DatabaseMetaData dbmData = conn.getMetaData(); - boolean isSnapshot = buildVersion.contains("SNAPSHOT"); + String driverVersion = dbmData.getDriverVersion(); - // Removing all dots & chars easy for comparing. - driverVersion = driverVersion.replaceAll("[^0-9]", ""); - buildVersion = buildVersion.replaceAll("[^0-9]", ""); + boolean isSnapshot = buildVersion.contains("SNAPSHOT"); - // Not comparing last build number. We will compare only major.minor.patch - driverVersion = driverVersion.substring(0, 3); - buildVersion = buildVersion.substring(0, 3); + // Removing all dots & chars easy for comparing. + driverVersion = driverVersion.replaceAll("[^0-9]", ""); + buildVersion = buildVersion.replaceAll("[^0-9]", ""); - int intBuildVersion = Integer.valueOf(buildVersion); - int intDriverVersion = Integer.valueOf(driverVersion); + // Not comparing last build number. We will compare only major.minor.patch + driverVersion = driverVersion.substring(0, 3); + buildVersion = buildVersion.substring(0, 3); - if (isSnapshot) { - assertTrue(intDriverVersion < intBuildVersion, TestResource.getResource("R_buildVersionError")); - } else { - assertTrue(intDriverVersion == intBuildVersion, TestResource.getResource("R_buildVersionError")); - } + int intBuildVersion = Integer.valueOf(buildVersion); + int intDriverVersion = Integer.valueOf(driverVersion); + if (isSnapshot) { + assertTrue(intDriverVersion < intBuildVersion, TestResource.getResource("R_buildVersionError")); + } else { + assertTrue(intDriverVersion == intBuildVersion, TestResource.getResource("R_buildVersionError")); + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } /** @@ -118,10 +125,14 @@ public void testDriverVersion() throws SQLException, IOException { */ @Test public void testGetURL() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - String url = databaseMetaData.getURL(); - url = url.toLowerCase(); - assertFalse(url.contains("password"), TestResource.getResource("R_getURLContainsPwd")); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + DatabaseMetaData databaseMetaData = conn.getMetaData(); + String url = databaseMetaData.getURL(); + url = url.toLowerCase(); + assertFalse(url.contains("password"), TestResource.getResource("R_getURLContainsPwd")); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } /** @@ -131,31 +142,36 @@ public void testGetURL() throws SQLException { */ @Test public void testDBUserLogin() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + DatabaseMetaData databaseMetaData = conn.getMetaData(); - String connectionString = getConfiguredProperty("mssql_jdbc_test_connection_properties"); + String connectionString = getConfiguredProperty("mssql_jdbc_test_connection_properties"); - connectionString = connectionString.toLowerCase(); + connectionString = connectionString.toLowerCase(); - int startIndex = 0; - int endIndex = 0; + int startIndex = 0; + int endIndex = 0; - if (connectionString.contains("username")) { - startIndex = connectionString.indexOf("username="); - endIndex = connectionString.indexOf(";", startIndex); - startIndex = startIndex + "username=".length(); - } else if (connectionString.contains("user")) { - startIndex = connectionString.indexOf("user="); - endIndex = connectionString.indexOf(";", startIndex); - startIndex = startIndex + "user=".length(); - } + if (connectionString.contains("username")) { + startIndex = connectionString.indexOf("username="); + endIndex = connectionString.indexOf(";", startIndex); + startIndex = startIndex + "username=".length(); + } else if (connectionString.contains("user")) { + startIndex = connectionString.indexOf("user="); + endIndex = connectionString.indexOf(";", startIndex); + startIndex = startIndex + "user=".length(); + } - String userFromConnectionString = connectionString.substring(startIndex, endIndex); - String userName = databaseMetaData.getUserName(); + String userFromConnectionString = connectionString.substring(startIndex, endIndex); + String userName = databaseMetaData.getUserName(); - assertNotNull(userName, TestResource.getResource("R_userNameNull")); + assertNotNull(userName, TestResource.getResource("R_userNameNull")); - assertTrue(userName.equalsIgnoreCase(userFromConnectionString), TestResource.getResource("R_userNameNotMatch")); + assertTrue(userName.equalsIgnoreCase(userFromConnectionString), + TestResource.getResource("R_userNameNotMatch")); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } /** @@ -165,14 +181,15 @@ public void testDBUserLogin() throws SQLException { */ @Test public void testDBSchema() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); ResultSet rs = conn.getMetaData().getSchemas()) { - ResultSet rs = databaseMetaData.getSchemas(); - - MessageFormat form = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[] msgArgs = {"Schema"}; - while (rs.next()) { - assertTrue(!StringUtils.isEmpty(rs.getString(1)), form.format(msgArgs)); + MessageFormat form = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[] msgArgs = {"Schema"}; + while (rs.next()) { + assertTrue(!StringUtils.isEmpty(rs.getString(1)), form.format(msgArgs)); + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } } @@ -187,44 +204,50 @@ public void testDBSchemasForDashedCatalogName() throws SQLException { UUID id = UUID.randomUUID(); String testCatalog = "dash-catalog" + id; String testSchema = "some-schema" + id; - - try (Statement stmt = connection.createStatement()) { - try (Connection dashConn = DriverManager.getConnection(connectionString); - Statement dashStatement = dashConn.createStatement()) { - - Utils.dropDatabaseIfExists(testCatalog, stmt); - stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); - - dashStatement.execute(String.format("USE [%s]", testCatalog)); - dashStatement.execute(String.format("CREATE SCHEMA [%s]", testSchema)); - - DatabaseMetaData databaseMetaData = connection.getMetaData(); - ResultSet rs = databaseMetaData.getSchemas(testCatalog, null); - - MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[] schemaMsgArgs = {"Schema"}; - - boolean hasResults = false; - boolean hasDashCatalogSchema = false; - while (rs.next()) { - hasResults = true; - String schemaName = rs.getString(1); - assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); - String catalogName = rs.getString(2); - if (schemaName.equals(testSchema)) { - hasDashCatalogSchema = true; - assertEquals(catalogName, testCatalog); - } else { - assertNull(catalogName); - } + ResultSet rs = null; + + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + Utils.dropDatabaseIfExists(testCatalog, stmt); + stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); + + stmt.execute(String.format("USE [%s]", testCatalog)); + stmt.execute(String.format("CREATE SCHEMA [%s]", testSchema)); + + rs = conn.getMetaData().getSchemas(testCatalog, null); + + MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[] schemaMsgArgs = {"Schema"}; + + boolean hasResults = false; + boolean hasDashCatalogSchema = false; + while (rs.next()) { + hasResults = true; + String schemaName = rs.getString(1); + assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); + String catalogName = rs.getString(2); + if (schemaName.equals(testSchema)) { + hasDashCatalogSchema = true; + assertEquals(catalogName, testCatalog); + } else { + assertNull(catalogName); } + } + + MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); - MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); + MessageFormat dashCatalogFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + assertTrue(hasDashCatalogSchema, dashCatalogFormat.format(new Object[] {testSchema})); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - MessageFormat dashCatalogFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - assertTrue(hasDashCatalogSchema, dashCatalogFormat.format(new Object[] {testSchema})); - } finally { + } finally { + if (null != rs) { + rs.close(); + } + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { Utils.dropDatabaseIfExists(testCatalog, stmt); } } @@ -242,37 +265,43 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { String testCatalog = "dash-catalog" + id; String testSchema = "some-schema" + id; - try (Statement stmt = connection.createStatement()) { - try (Connection dashConn = DriverManager.getConnection(connectionString); - Statement dashStatement = dashConn.createStatement()) { + ResultSet rs = null; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + Utils.dropDatabaseIfExists(testCatalog, stmt); + stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); + + stmt.execute(String.format("USE [%s]", testCatalog)); + stmt.execute(String.format("CREATE SCHEMA [%s]", testSchema)); + + rs = conn.getMetaData().getSchemas(testCatalog, "some-%"); + + MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[] schemaMsgArgs = {testSchema}; + Object[] catalogMsgArgs = {testCatalog}; + + boolean hasResults = false; + while (rs.next()) { + hasResults = true; + String schemaName = rs.getString(1); + String catalogName = rs.getString(2); + assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); + assertTrue(!StringUtils.isEmpty(catalogName), schemaEmptyFormat.format(catalogMsgArgs)); + assertEquals(schemaName, schemaMsgArgs[0]); + assertEquals(catalogName, catalogMsgArgs[0]); + } - Utils.dropDatabaseIfExists(testCatalog, stmt); - stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); - - dashStatement.execute(String.format("USE [%s]", testCatalog)); - dashStatement.execute(String.format("CREATE SCHEMA [%s]", testSchema)); - - DatabaseMetaData databaseMetaData = connection.getMetaData(); - ResultSet rs = databaseMetaData.getSchemas(testCatalog, "some-%"); - - MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[] schemaMsgArgs = {testSchema}; - Object[] catalogMsgArgs = {testCatalog}; - - boolean hasResults = false; - while (rs.next()) { - hasResults = true; - String schemaName = rs.getString(1); - String catalogName = rs.getString(2); - assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); - assertTrue(!StringUtils.isEmpty(catalogName), schemaEmptyFormat.format(catalogMsgArgs)); - assertEquals(schemaName, schemaMsgArgs[0]); - assertEquals(catalogName, catalogMsgArgs[0]); - } + MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); - } finally { + } finally { + if (null != rs) { + rs.close(); + } + + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { Utils.dropDatabaseIfExists(testCatalog, stmt); } } @@ -284,22 +313,37 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { * @throws SQLException */ @Test + /* + try (ResultSet rsCatalog = connection.getMetaData().getCatalogs(); ResultSet rs = connection.getMetaData() + .getTables(rsCatalog.getString("TABLE_CAT"), null, "%", new String[] {"TABLE"})) { +*/ public void testDBTables() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - ResultSet rsCatalog = databaseMetaData.getCatalogs(); + ResultSet rsCatalog = null; + ResultSet rs = null; + try (Connection con = DriverManager.getConnection(connectionString)) { + DatabaseMetaData databaseMetaData = con.getMetaData(); + rsCatalog = databaseMetaData.getCatalogs(); - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"catalog"}; - assertTrue(rsCatalog.next(), form1.format(msgArgs1)); + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"catalog"}; + assertTrue(rsCatalog.next(), form1.format(msgArgs1)); - String[] types = {"TABLE"}; - ResultSet rs = databaseMetaData.getTables(rsCatalog.getString("TABLE_CAT"), null, "%", types); + String[] types = {"TABLE"}; + rs = databaseMetaData.getTables(rsCatalog.getString("TABLE_CAT"), null, "%", types); - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[] msgArgs2 = {"Table"}; - while (rs.next()) { - assertTrue(!StringUtils.isEmpty(rs.getString("TABLE_NAME")), form2.format(msgArgs2)); + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[] msgArgs2 = {"Table"}; + while (rs.next()) { + assertTrue(!StringUtils.isEmpty(rs.getString("TABLE_NAME")), form2.format(msgArgs2)); + } + } finally { + if (null != rsCatalog) { + rsCatalog.close(); + } + if (null != rs) { + rs.close(); + } } } @@ -316,32 +360,49 @@ public void testDBTables() throws SQLException { */ @Test public void testGetDBColumn() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - String[] types = {"TABLE"}; - ResultSet rs = databaseMetaData.getTables(null, null, "%", types); - - // Fetch one table - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"table"}; - assertTrue(rs.next(), form1.format(msgArgs1)); - - // Go through all columns. - ResultSet rs1 = databaseMetaData.getColumns(null, null, rs.getString("TABLE_NAME"), "%"); - - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"Data Type"}, {"Type"}, - {"Column Size"}, {"Nullable value"}, {"IS_NULLABLE"}, {"IS_AUTOINCREMENT"}}; - while (rs1.next()) { - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); - assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); - assertTrue(!StringUtils.isEmpty(rs1.getString("DATA_TYPE")), form2.format(msgArgs2[4])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TYPE_NAME")), form2.format(msgArgs2[5])); - assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_SIZE")), form2.format(msgArgs2[6])); - assertTrue(!StringUtils.isEmpty(rs1.getString("NULLABLE")), form2.format(msgArgs2[7])); // 11 - assertTrue(!StringUtils.isEmpty(rs1.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 18 - assertTrue(!StringUtils.isEmpty(rs1.getString("IS_AUTOINCREMENT")), form2.format(msgArgs2[9])); // 22 + + ResultSet rs = null; + ResultSet rs1 = null; + + try (Connection conn = DriverManager.getConnection(connectionString)) { + DatabaseMetaData databaseMetaData = conn.getMetaData(); + + String[] types = {"TABLE"}; + rs = databaseMetaData.getTables(null, null, "%", types); + + + // Fetch one table + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"table"}; + assertTrue(rs.next(), form1.format(msgArgs1)); + + // Go through all columns. + rs1 = databaseMetaData.getColumns(null, null, rs.getString("TABLE_NAME"), "%"); + + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"Data Type"}, {"Type"}, + {"Column Size"}, {"Nullable value"}, {"IS_NULLABLE"}, {"IS_AUTOINCREMENT"}}; + while (rs1.next()) { + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); + assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); + assertTrue(!StringUtils.isEmpty(rs1.getString("DATA_TYPE")), form2.format(msgArgs2[4])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TYPE_NAME")), form2.format(msgArgs2[5])); + assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_SIZE")), form2.format(msgArgs2[6])); + assertTrue(!StringUtils.isEmpty(rs1.getString("NULLABLE")), form2.format(msgArgs2[7])); // 11 + assertTrue(!StringUtils.isEmpty(rs1.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 18 + assertTrue(!StringUtils.isEmpty(rs1.getString("IS_AUTOINCREMENT")), form2.format(msgArgs2[9])); // 22 + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != rs) { + rs.close(); + } + if (null != rs1) { + rs1.close(); + } } } @@ -356,30 +417,37 @@ public void testGetDBColumn() throws SQLException { */ @Test public void testGetColumnPrivileges() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - String[] types = {"TABLE"}; - ResultSet rsTables = databaseMetaData.getTables(null, null, "%", types); - - // Fetch one table - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"table"}; - assertTrue(rsTables.next(), form1.format(msgArgs1)); - - // Go through all columns. - ResultSet rs1 = databaseMetaData.getColumnPrivileges(null, null, rsTables.getString("TABLE_NAME"), "%"); - - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"GRANTOR"}, {"GRANTEE"}, {"PRIVILEGE"}, - {"IS_GRANTABLE"}}; - while (rs1.next()) { - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); - assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); - assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTOR")), form2.format(msgArgs2[4])); - assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTEE")), form2.format(msgArgs2[5])); - assertTrue(!StringUtils.isEmpty(rs1.getString("PRIVILEGE")), form2.format(msgArgs2[6])); - assertTrue(!StringUtils.isEmpty(rs1.getString("IS_GRANTABLE")), form2.format(msgArgs2[7])); + + ResultSet rsTables = null; + ResultSet rs1 = null; + + try (Connection conn = DriverManager.getConnection(connectionString)) { + DatabaseMetaData databaseMetaData = conn.getMetaData(); + String[] types = {"TABLE"}; + rsTables = databaseMetaData.getTables(null, null, "%", types); + + // Fetch one table + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"table"}; + assertTrue(rsTables.next(), form1.format(msgArgs1)); + + rs1 = databaseMetaData.getColumnPrivileges(null, null, rsTables.getString("TABLE_NAME"), "%"); + + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"GRANTOR"}, {"GRANTEE"}, + {"PRIVILEGE"}, {"IS_GRANTABLE"}}; + while (rs1.next()) { + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); + assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); + assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTOR")), form2.format(msgArgs2[4])); + assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTEE")), form2.format(msgArgs2[5])); + assertTrue(!StringUtils.isEmpty(rs1.getString("PRIVILEGE")), form2.format(msgArgs2[6])); + assertTrue(!StringUtils.isEmpty(rs1.getString("IS_GRANTABLE")), form2.format(msgArgs2[7])); + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } } @@ -392,9 +460,8 @@ public void testGetColumnPrivileges() throws SQLException { */ @Test public void testGetFunctionsWithWrongParams() throws SQLException { - try { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - databaseMetaData.getFunctions("", null, "xp_%"); + try (Connection conn = DriverManager.getConnection(connectionString)) { + conn.getMetaData().getFunctions("", null, "xp_%"); assertTrue(false, TestResource.getResource("R_noSchemaShouldFail")); } catch (Exception ae) { @@ -408,22 +475,24 @@ public void testGetFunctionsWithWrongParams() throws SQLException { */ @Test public void testGetFunctions() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - ResultSet rs = databaseMetaData.getFunctions(null, null, "xp_%"); - - MessageFormat form = new MessageFormat(TestResource.getResource("R_nameNull")); - Object[][] msgArgs = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"NUM_INPUT_PARAMS"}, - {"NUM_OUPUT_PARAMS"}, {"NUM_RESULT_SETS"}, {"FUNCTION_TYPE"}}; - while (rs.next()) { - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_CAT")), form.format(msgArgs[0])); - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_SCHEM")), form.format(msgArgs[1])); - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_NAME")), form.format(msgArgs[2])); - assertTrue(!StringUtils.isEmpty(rs.getString("NUM_INPUT_PARAMS")), form.format(msgArgs[3])); - assertTrue(!StringUtils.isEmpty(rs.getString("NUM_OUTPUT_PARAMS")), form.format(msgArgs[4])); - assertTrue(!StringUtils.isEmpty(rs.getString("NUM_RESULT_SETS")), form.format(msgArgs[5])); - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_TYPE")), form.format(msgArgs[6])); + try (Connection conn = DriverManager.getConnection(connectionString); + ResultSet rs = conn.getMetaData().getFunctions(null, null, "xp_%")) { + + MessageFormat form = new MessageFormat(TestResource.getResource("R_nameNull")); + Object[][] msgArgs = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"NUM_INPUT_PARAMS"}, + {"NUM_OUPUT_PARAMS"}, {"NUM_RESULT_SETS"}, {"FUNCTION_TYPE"}}; + while (rs.next()) { + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_CAT")), form.format(msgArgs[0])); + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_SCHEM")), form.format(msgArgs[1])); + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_NAME")), form.format(msgArgs[2])); + assertTrue(!StringUtils.isEmpty(rs.getString("NUM_INPUT_PARAMS")), form.format(msgArgs[3])); + assertTrue(!StringUtils.isEmpty(rs.getString("NUM_OUTPUT_PARAMS")), form.format(msgArgs[4])); + assertTrue(!StringUtils.isEmpty(rs.getString("NUM_RESULT_SETS")), form.format(msgArgs[5])); + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_TYPE")), form.format(msgArgs[6])); + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } - rs.close(); } /** @@ -433,32 +502,44 @@ public void testGetFunctions() throws SQLException { */ @Test public void testGetFunctionColumns() throws SQLException { - DatabaseMetaData databaseMetaData = connection.getMetaData(); - ResultSet rsFunctions = databaseMetaData.getFunctions(null, null, "%"); - - // Fetch one Function - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"function"}; - assertTrue(rsFunctions.next(), form1.format(msgArgs1)); - - // Go through all columns. - ResultSet rs = databaseMetaData.getFunctionColumns(null, null, rsFunctions.getString("FUNCTION_NAME"), "%"); - - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameNull")); - Object[][] msgArgs2 = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"COLUMN_NAME"}, - {"COLUMN_TYPE"}, {"DATA_TYPE"}, {"TYPE_NAME"}, {"NULLABLE"}, {"IS_NULLABLE"}}; - while (rs.next()) { - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_CAT")), form2.format(msgArgs2[0])); - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_SCHEM")), form2.format(msgArgs2[1])); - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_NAME")), form2.format(msgArgs2[2])); - assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); - assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_TYPE")), form2.format(msgArgs2[4])); - assertTrue(!StringUtils.isEmpty(rs.getString("DATA_TYPE")), form2.format(msgArgs2[5])); - assertTrue(!StringUtils.isEmpty(rs.getString("TYPE_NAME")), form2.format(msgArgs2[6])); - assertTrue(!StringUtils.isEmpty(rs.getString("NULLABLE")), form2.format(msgArgs2[7])); // 12 - assertTrue(!StringUtils.isEmpty(rs.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 19 + ResultSet rsFunctions = null; + ResultSet rs = null; + try (Connection conn = DriverManager.getConnection(connectionString)) { + + DatabaseMetaData databaseMetaData = conn.getMetaData(); + + rsFunctions = databaseMetaData.getFunctions(null, null, "%"); + + // Fetch one Function + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"function"}; + assertTrue(rsFunctions.next(), form1.format(msgArgs1)); + + rs = databaseMetaData.getFunctionColumns(null, null, rsFunctions.getString("FUNCTION_NAME"), "%"); + + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameNull")); + Object[][] msgArgs2 = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"COLUMN_NAME"}, + {"COLUMN_TYPE"}, {"DATA_TYPE"}, {"TYPE_NAME"}, {"NULLABLE"}, {"IS_NULLABLE"}}; + while (rs.next()) { + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_CAT")), form2.format(msgArgs2[0])); + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_SCHEM")), form2.format(msgArgs2[1])); + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_NAME")), form2.format(msgArgs2[2])); + assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); + assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_TYPE")), form2.format(msgArgs2[4])); + assertTrue(!StringUtils.isEmpty(rs.getString("DATA_TYPE")), form2.format(msgArgs2[5])); + assertTrue(!StringUtils.isEmpty(rs.getString("TYPE_NAME")), form2.format(msgArgs2[6])); + assertTrue(!StringUtils.isEmpty(rs.getString("NULLABLE")), form2.format(msgArgs2[7])); // 12 + assertTrue(!StringUtils.isEmpty(rs.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 19 + } + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + if (null != rsFunctions) { + rsFunctions.close(); + } + if (null != rs) { + rs.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 6e4bf7f97..1c3f8dc52 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -13,7 +13,6 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLTimeoutException; -import java.util.Random; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -58,7 +57,7 @@ public void testInt() throws SQLException { tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(12); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -87,7 +86,7 @@ public void testDate() throws SQLException { tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(date); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -112,7 +111,7 @@ public void testMoney() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(new BigDecimal(numeric[14])); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -137,7 +136,7 @@ public void testSmallInt() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Short.valueOf(numeric[2])); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -161,13 +160,12 @@ public void testSmallInt() throws SQLException { */ @Test public void testBigInt() throws SQLException { - Random r = new Random(); tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Long.parseLong(numeric[4])); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -192,7 +190,7 @@ public void testBoolean() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Boolean.parseBoolean(numeric[0])); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -217,7 +215,7 @@ public void testFloat() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Float.parseFloat(numeric[1])); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -242,7 +240,7 @@ public void testNvarChar() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String colValue = "س"; tvp.addRow(colValue); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -272,7 +270,7 @@ public void testVarChar8000() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -302,7 +300,7 @@ public void testLongVarChar() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); try { @@ -333,7 +331,7 @@ public void testDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(timestamp); - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -363,7 +361,7 @@ public void testNull() throws SQLException { assertTrue(e.getMessage().startsWith("Use of TVPs containing null sql_variant columns is not supported.")); } - pstmt = (SQLServerPreparedStatement) connection + pstmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -389,7 +387,7 @@ public void testIntStoredProcedure() throws SQLException { tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(timestamp); - SQLServerCallableStatement Cstatement = (SQLServerCallableStatement) connection.prepareCall(sql); + SQLServerCallableStatement Cstatement = (SQLServerCallableStatement) conn.prepareCall(sql); Cstatement.setStructured(1, tvpName, tvp); Cstatement.execute(); rs = (SQLServerResultSet) stmt.executeQuery("select * from " + destTable); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java index 81a0980d0..962f454b7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java @@ -4,6 +4,8 @@ */ package com.microsoft.sqlserver.jdbc.fips; +import static org.junit.Assert.fail; + import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; @@ -43,10 +45,9 @@ public static void init() { */ @Test public void fipsTrustServerCertificateTest() throws Exception { - try { - Properties props = buildConnectionProperties(); - props.setProperty("TrustServerCertificate", "true"); - Connection con = PrepUtil.getConnection(connectionString, props); + Properties props = buildConnectionProperties(); + props.setProperty("TrustServerCertificate", "true"); + try (Connection con = PrepUtil.getConnection(connectionString, props)) { Assertions.fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (SQLException e) { Assertions.assertTrue(e.getMessage().contains(TestResource.getResource("R_invalidFipsConfig")), @@ -61,10 +62,9 @@ public void fipsTrustServerCertificateTest() throws Exception { */ @Test public void fipsEncryptTest() throws Exception { - try { - Properties props = buildConnectionProperties(); - props.setProperty("encrypt", "false"); - Connection con = PrepUtil.getConnection(connectionString, props); + Properties props = buildConnectionProperties(); + props.setProperty("encrypt", "false"); + try (Connection con = PrepUtil.getConnection(connectionString, props)) { Assertions.fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (SQLException e) { Assertions.assertTrue(e.getMessage().contains(TestResource.getResource("R_invalidFipsConfig")), @@ -83,10 +83,11 @@ public void fipsPropertyTest() throws Exception { props.remove("fips"); props.remove("trustStoreType"); props.remove("encrypt"); - Connection con = PrepUtil.getConnection(connectionString, props); - Assertions.assertTrue(!StringUtils.isEmpty(con.getSchema())); - con.close(); - con = null; + try (Connection con = PrepUtil.getConnection(connectionString, props)) { + Assertions.assertTrue(!StringUtils.isEmpty(con.getSchema())); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } /** @@ -101,10 +102,11 @@ public void fipsDataSourcePropertyTest() throws Exception { ds.setFIPS(false); ds.setEncrypt(false); ds.setTrustStoreType("JKS"); - Connection con = ds.getConnection(); - Assertions.assertTrue(!StringUtils.isEmpty(con.getSchema())); - con.close(); - con = null; + try (Connection con = ds.getConnection()) { + Assertions.assertTrue(!StringUtils.isEmpty(con.getSchema())); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } } /** @@ -112,12 +114,11 @@ public void fipsDataSourcePropertyTest() throws Exception { */ @Test public void fipsDatSourceEncrypt() { - try { - SQLServerDataSource ds = new SQLServerDataSource(); - setDataSourceProperties(ds); - ds.setEncrypt(false); - Connection con = ds.getConnection(); + SQLServerDataSource ds = new SQLServerDataSource(); + setDataSourceProperties(ds); + ds.setEncrypt(false); + try (Connection con = ds.getConnection()) { Assertions.fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (SQLException e) { Assertions.assertTrue(e.getMessage().contains(TestResource.getResource("R_invalidFipsConfig")), @@ -132,11 +133,11 @@ public void fipsDatSourceEncrypt() { */ @Test public void fipsDataSourceTrustServerCertificateTest() throws Exception { - try { - SQLServerDataSource ds = new SQLServerDataSource(); - setDataSourceProperties(ds); - ds.setTrustServerCertificate(true); - Connection con = ds.getConnection(); + SQLServerDataSource ds = new SQLServerDataSource(); + setDataSourceProperties(ds); + ds.setTrustServerCertificate(true); + + try (Connection con = ds.getConnection()) { Assertions.fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (SQLException e) { Assertions.assertTrue(e.getMessage().contains(TestResource.getResource("R_invalidFipsConfig")), @@ -244,5 +245,4 @@ else if (strParam.startsWith("user")) { return dataSoureParam; } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java index 207a1fd4c..60baafb42 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java @@ -181,23 +181,24 @@ public void testAllcolumns() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); - - Object[] expected = new Object[9]; - - expected[0] = 1234; - expected[1] = false; - expected[2] = "a"; - expected[3] = d; - expected[4] = myTimestamp; - expected[5] = 123.45; - expected[6] = "b"; - expected[7] = "varc"; - expected[8] = "''"; - - rs.next(); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i].toString(), rs.getObject(i + 1).toString()); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + Object[] expected = new Object[9]; + + expected[0] = 1234; + expected[1] = false; + expected[2] = "a"; + expected[3] = d; + expected[4] = myTimestamp; + expected[5] = 123.45; + expected[6] = "b"; + expected[7] = "varc"; + expected[8] = "''"; + + rs.next(); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i].toString(), rs.getObject(i + 1).toString()); + } } } } @@ -226,24 +227,25 @@ public void testMixColumns() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); - - Object[] expected = new Object[9]; - - expected[0] = 1234; - expected[1] = false; - expected[2] = "a"; - expected[3] = d; - expected[4] = myTimestamp; - expected[5] = 123.45; - expected[6] = "b"; - expected[7] = "varc"; - expected[8] = "varcmax"; - - rs.next(); - for (int i = 0; i < expected.length; i++) { - if (null != rs.getObject(i + 1)) { - assertEquals(expected[i].toString(), rs.getObject(i + 1).toString()); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + Object[] expected = new Object[9]; + + expected[0] = 1234; + expected[1] = false; + expected[2] = "a"; + expected[3] = d; + expected[4] = myTimestamp; + expected[5] = 123.45; + expected[6] = "b"; + expected[7] = "varc"; + expected[8] = "varcmax"; + + rs.next(); + for (int i = 0; i < expected.length; i++) { + if (null != rs.getObject(i + 1)) { + assertEquals(expected[i].toString(), rs.getObject(i + 1).toString()); + } } } } @@ -272,22 +274,23 @@ public void testNullOrEmptyColumns() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - Object[] expected = new Object[9]; + Object[] expected = new Object[9]; - expected[0] = 1234; - expected[1] = false; - expected[2] = null; - expected[3] = null; - expected[4] = null; - expected[5] = 123.45; - expected[6] = " "; + expected[0] = 1234; + expected[1] = false; + expected[2] = null; + expected[3] = null; + expected[4] = null; + expected[5] = 123.45; + expected[6] = " "; - rs.next(); - for (int i = 0; i < expected.length; i++) { - if (null != rs.getObject(i + 1)) { - assertEquals(expected[i], rs.getObject(i + 1)); + rs.next(); + for (int i = 0; i < expected.length; i++) { + if (null != rs.getObject(i + 1)) { + assertEquals(expected[i], rs.getObject(i + 1)); + } } } } @@ -310,23 +313,24 @@ public void testAllFilledColumns() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - Object[] expected = new Object[9]; + Object[] expected = new Object[9]; - expected[0] = 1234; - expected[1] = false; - expected[2] = "a"; - expected[3] = null; - expected[4] = null; - expected[5] = 123.45; - expected[6] = "b"; - expected[7] = "varc"; - expected[8] = "sadf"; + expected[0] = 1234; + expected[1] = false; + expected[2] = "a"; + expected[3] = null; + expected[4] = null; + expected[5] = 123.45; + expected[6] = "b"; + expected[7] = "varc"; + expected[8] = "sadf"; - rs.next(); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], rs.getObject(i + 1)); + rs.next(); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], rs.getObject(i + 1)); + } } } } @@ -351,10 +355,11 @@ public void testSquareBracketAgainstDB() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName); - rs.next(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName)) { + rs.next(); - assertEquals(1, rs.getObject(1)); + assertEquals(1, rs.getObject(1)); + } } } @@ -378,10 +383,11 @@ public void testDoubleQuoteAgainstDB() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + doubleQuoteTableName); - rs.next(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + doubleQuoteTableName)) { + rs.next(); - assertEquals(1, rs.getObject(1)); + assertEquals(1, rs.getObject(1)); + } } } @@ -407,10 +413,11 @@ public void testSchemaAgainstDB() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + schemaTableName); - rs.next(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + schemaTableName)) { + rs.next(); - assertEquals(1, rs.getObject(1)); + assertEquals(1, rs.getObject(1)); + } } } @@ -434,10 +441,11 @@ public void testColumnNameMixAgainstDB() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName); - rs.next(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName)) { + rs.next(); - assertEquals(1, rs.getObject(1)); + assertEquals(1, rs.getObject(1)); + } } } @@ -470,23 +478,24 @@ public void testAllColumnsLargeBatch() throws Exception { pstmt.executeLargeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - Object[] expected = new Object[9]; + Object[] expected = new Object[9]; - expected[0] = 1234; - expected[1] = false; - expected[2] = "a"; - expected[3] = d; - expected[4] = myTimestamp; - expected[5] = 123.45; - expected[6] = "b"; - expected[7] = "varc"; - expected[8] = "''"; + expected[0] = 1234; + expected[1] = false; + expected[2] = "a"; + expected[3] = d; + expected[4] = myTimestamp; + expected[5] = 123.45; + expected[6] = "b"; + expected[7] = "varc"; + expected[8] = "''"; - rs.next(); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i].toString(), rs.getObject(i + 1).toString()); + rs.next(); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i].toString(), rs.getObject(i + 1).toString()); + } } } } @@ -611,12 +620,13 @@ public void testNonSupportedColumns() throws Exception { pstmt.executeBatch(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + unsupportedTableName); - rs.next(); - assertEquals(g1.toString(), Geometry.STGeomFromWKB((byte[]) rs.getObject(1)).toString()); - assertEquals(g2.toString(), Geography.STGeomFromWKB((byte[]) rs.getObject(2)).toString()); - assertEquals(myTimestamp, rs.getObject(3)); - assertEquals(myTimestamp, rs.getObject(4)); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + unsupportedTableName)) { + rs.next(); + assertEquals(g1.toString(), Geometry.STGeomFromWKB((byte[]) rs.getObject(1)).toString()); + assertEquals(g2.toString(), Geography.STGeomFromWKB((byte[]) rs.getObject(2)).toString()); + assertEquals(myTimestamp, rs.getObject(3)); + assertEquals(myTimestamp, rs.getObject(4)); + } } } 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 d8194ef46..f44c8bfe3 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -32,6 +32,7 @@ @RunWith(JUnitPlatform.class) public class BatchExecutionWithNullTest extends AbstractTest { + static Connection conn = null; static Statement stmt = null; static Connection connection = null; static PreparedStatement pstmt = null; @@ -51,8 +52,9 @@ public void testAddBatch2() throws SQLException { int updateCountlen = 0; int key = 42; - // this is the minimum sequence, I've found to trigger the error - pstmt = connection.prepareStatement(sPrepStmt); + // this is the minimum sequence, I've found to trigger the error\ + conn = DriverManager.getConnection(connectionString); + pstmt = conn.prepareStatement(sPrepStmt); pstmt.setInt(1, key++); pstmt.setNull(2, Types.VARCHAR); pstmt.addBatch(); @@ -117,10 +119,9 @@ public void testSetup() throws TestAbortedException, Exception { @AfterAll public static void terminateVariation() throws SQLException { - connection = DriverManager.getConnection(connectionString); - - SQLServerStatement stmt = (SQLServerStatement) connection.createStatement(); - Utils.dropTableIfExists("esimple", stmt); + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + Utils.dropTableIfExists("esimple", stmt); + } if (null != pstmt) { pstmt.close(); @@ -134,8 +135,8 @@ public static void terminateVariation() throws SQLException { if (null != rs) { rs.close(); } - if (null != connection) { - connection.close(); + if (null != conn) { + conn.close(); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java index e8a7b7008..942f0b248 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java @@ -36,10 +36,6 @@ @RunWith(JUnitPlatform.class) public class RegressionTest extends AbstractTest { static Connection con = null; - static PreparedStatement pstmt1 = null; - static PreparedStatement pstmt2 = null; - static PreparedStatement pstmt3 = null; - static PreparedStatement pstmt4 = null; /** * Setup before test @@ -49,10 +45,8 @@ public class RegressionTest extends AbstractTest { @BeforeAll public static void setupTest() throws SQLException { con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - Utils.dropTableIfExists("x", stmt); - if (null != stmt) { - stmt.close(); + try (Statement stmt = con.createStatement()) { + Utils.dropTableIfExists("x", stmt); } } @@ -63,24 +57,14 @@ public static void setupTest() throws SQLException { */ @Test public void createViewTest() throws SQLException { - try { - pstmt1 = con.prepareStatement("create view x as select 1 a"); - pstmt2 = con.prepareStatement("drop view x"); + try (PreparedStatement pstmt1 = con.prepareStatement("create view x as select 1 a"); + PreparedStatement pstmt2 = con.prepareStatement("drop view x")) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { fail(TestResource.getResource("R_createDropViewFailed") + TestResource.getResource("R_errorMessage") + e.getMessage()); } - - finally { - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - } } /** @@ -90,24 +74,14 @@ public void createViewTest() throws SQLException { */ @Test public void createSchemaTest() throws SQLException { - try { - pstmt1 = con.prepareStatement("create schema x"); - pstmt2 = con.prepareStatement("drop schema x"); + try (PreparedStatement pstmt1 = con.prepareStatement("create schema x"); + PreparedStatement pstmt2 = con.prepareStatement("drop schema x")) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { fail(TestResource.getResource("R_createDropSchemaFailed") + TestResource.getResource("R_errorMessage") + e.getMessage()); } - - finally { - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - } } /** @@ -117,24 +91,14 @@ public void createSchemaTest() throws SQLException { */ @Test public void createTableTest() throws SQLException { - try { - pstmt1 = con.prepareStatement("create table x (col1 int)"); - pstmt2 = con.prepareStatement("drop table x"); + try (PreparedStatement pstmt1 = con.prepareStatement("create table x (col1 int)"); + PreparedStatement pstmt2 = con.prepareStatement("drop table x")) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { fail(TestResource.getResource("R_createDropTableFailed") + TestResource.getResource("R_errorMessage") + e.getMessage()); } - - finally { - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - } } /** @@ -144,10 +108,9 @@ public void createTableTest() throws SQLException { */ @Test public void alterTableTest() throws SQLException { - try { - pstmt1 = con.prepareStatement("create table x (col1 int)"); - pstmt2 = con.prepareStatement("ALTER TABLE x ADD column_name char;"); - pstmt3 = con.prepareStatement("drop table x"); + try (PreparedStatement pstmt1 = con.prepareStatement("create table x (col1 int)"); + PreparedStatement pstmt2 = con.prepareStatement("ALTER TABLE x ADD column_name char;"); + PreparedStatement pstmt3 = con.prepareStatement("drop table x")) { pstmt1.execute(); pstmt2.execute(); pstmt3.execute(); @@ -155,18 +118,6 @@ public void alterTableTest() throws SQLException { fail(TestResource.getResource("R_createDropAlterTableFailed") + TestResource.getResource("R_errorMessage") + e.getMessage()); } - - finally { - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - if (null != pstmt3) { - pstmt3.close(); - } - } } /** @@ -176,11 +127,10 @@ public void alterTableTest() throws SQLException { */ @Test public void grantTest() throws SQLException { - try { - pstmt1 = con.prepareStatement("create table x (col1 int)"); - pstmt2 = con.prepareStatement("grant select on x to public"); - pstmt3 = con.prepareStatement("revoke select on x from public"); - pstmt4 = con.prepareStatement("drop table x"); + try (PreparedStatement pstmt1 = con.prepareStatement("create table x (col1 int)"); + PreparedStatement pstmt2 = con.prepareStatement("grant select on x to public"); + PreparedStatement pstmt3 = con.prepareStatement("revoke select on x from public"); + PreparedStatement pstmt4 = con.prepareStatement("drop table x")) { pstmt1.execute(); pstmt2.execute(); pstmt3.execute(); @@ -189,21 +139,6 @@ public void grantTest() throws SQLException { fail(TestResource.getResource("R_grantFailed") + TestResource.getResource("R_errorMessage") + e.getMessage()); } - - finally { - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - if (null != pstmt3) { - pstmt3.close(); - } - if (null != pstmt4) { - pstmt4.close(); - } - } } /** @@ -228,7 +163,6 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } Statement stmt = con.createStatement(); - PreparedStatement pstmt = null; ResultSet rs = null; Utils.dropTableIfExists("TEST_TABLE", stmt); @@ -258,8 +192,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { String[] values = {"a", "b", largeString, "d", "e"}; // insert five rows into the table; use a batch for each row - try { - pstmt = con.prepareStatement("insert into TEST_TABLE values (?,?)"); + try (PreparedStatement pstmt = con.prepareStatement("insert into TEST_TABLE values (?,?)")) { // 0,a pstmt.setInt(1, 0); pstmt.setNString(2, values[0]); @@ -294,8 +227,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { // check the data in the table Map selectedValues = new LinkedHashMap<>(); int id = 0; - try { - pstmt = con.prepareStatement("select * from TEST_TABLE;"); + try (PreparedStatement pstmt = con.prepareStatement("select * from TEST_TABLE;")) { try { rs = pstmt.executeQuery(); int i = 0; @@ -315,9 +247,6 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } } finally { Utils.dropTableIfExists("TEST_TABLE", stmt); - if (null != pstmt) { - pstmt.close(); - } if (null != stmt) { stmt.close(); } @@ -424,22 +353,13 @@ public void addBatchWithLargeStringTest() throws SQLException { */ @AfterAll public static void cleanup() throws SQLException { - Statement stmt = con.createStatement(); - Utils.dropTableIfExists("x", stmt); - Utils.dropTableIfExists("TEST_TABLE", stmt); - if (null != stmt) { - stmt.close(); + try (Statement stmt = con.createStatement()) { + Utils.dropTableIfExists("x", stmt); + Utils.dropTableIfExists("TEST_TABLE", stmt); } if (null != con) { con.close(); } - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - } private void modifyConnectionForBulkCopyAPI(SQLServerConnection con) throws Exception { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java index 8fbdeff2c..4876c0689 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java @@ -315,26 +315,10 @@ public void testResultSetWrapper() throws SQLException { */ @Test public void testGetterOnNull() throws SQLException { - Connection con = null; - Statement stmt = null; - ResultSet rs = null; - try { - con = DriverManager.getConnection(connectionString); - stmt = con.createStatement(); - rs = stmt.executeQuery("select null"); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select null")) { rs.next(); assertEquals(null, rs.getTime(1)); - } finally { - if (con != null) { - con.close(); - } - if (stmt != null) { - stmt.close(); - } - if (rs != null) { - rs.close(); - } } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java index 210d73e87..b95a7254b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java @@ -4,6 +4,8 @@ */ package com.microsoft.sqlserver.jdbc.tvp; +import static org.junit.Assert.fail; + import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; @@ -17,6 +19,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; +import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; @@ -54,33 +57,21 @@ public void testTVPResultSet() throws SQLException { private void testTVPResultSet(boolean setSelectMethod, Integer resultSetType, Integer resultSetConcurrency) throws SQLException { - setupVariation(); - - Connection connnection = null; - if (setSelectMethod) { - connnection = DriverManager.getConnection(connectionString + ";selectMethod=cursor;"); - } else { - connnection = DriverManager.getConnection(connectionString); + setupVariation(setSelectMethod, resultSetType, resultSetConcurrency); + + try (ResultSet rs = stmt.executeQuery("select * from " + tableSrc.getEscapedTableName()); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + tableDest.getEscapedTableName() + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); + + ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, + tableDest); + } catch (Exception e) { + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + } finally { + terminateVariation(); } - - Statement stmtement = null; - if (null != resultSetType || null != resultSetConcurrency) { - stmtement = connnection.createStatement(resultSetType, resultSetConcurrency); - } else { - stmtement = connnection.createStatement(); - } - - ResultSet rs = stmtement.executeQuery("select * from " + tableSrc.getEscapedTableName()); - - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connnection - .prepareStatement("INSERT INTO " + tableDest.getEscapedTableName() + " select * from ? ;"); - pstmt.setStructured(1, tvpName, rs); - pstmt.execute(); - - ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, - tableDest); - - terminateVariation(); } /** @@ -100,33 +91,18 @@ public void testTVPStoredProcedureResultSet() throws SQLException { private void testTVPStoredProcedureResultSet(boolean setSelectMethod, Integer resultSetType, 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); - } else { - stmtement = connnection.createStatement(); + setupVariation(setSelectMethod, resultSetType, resultSetConcurrency); + try (ResultSet rs = stmt.executeQuery("select * from " + tableSrc.getEscapedTableName()); + SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) conn + .prepareCall("{call " + procedureName + "(?)}")) { + Cstmt.setStructured(1, tvpName, rs); + Cstmt.execute(); + + ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, + tableDest); + } finally { + terminateVariation(); } - - ResultSet rs = stmtement.executeQuery("select * from " + tableSrc.getEscapedTableName()); - - String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) connnection.prepareCall(sql); - Cstmt.setStructured(1, tvpName, rs); - Cstmt.execute(); - - ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, - tableDest); - - terminateVariation(); } /** @@ -136,7 +112,7 @@ private void testTVPStoredProcedureResultSet(boolean setSelectMethod, Integer re */ @Test public void testTVPDataTable() throws SQLException { - setupVariation(); + setupVariation(false, null, null); SQLServerDataTable dt = new SQLServerDataTable(); @@ -153,10 +129,13 @@ public void testTVPDataTable() throws SQLException { dt.addRow(values); } - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + tableDest.getEscapedTableName() + " select * from ? ;"); - pstmt.setStructured(1, tvpName, dt); - pstmt.execute(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + tableDest.getEscapedTableName() + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, dt); + pstmt.execute(); + } finally { + terminateVariation(); + } } private static void createPreocedure(String procedureName, String destTable) throws SQLException { @@ -176,9 +155,19 @@ private static void createTVPS(String TVPName, String TVPDefinition) throws SQLE stmt.executeUpdate(TVPCreateCmd); } - private void setupVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); + private void setupVariation(boolean setSelectMethod, Integer resultSetType, Integer resultSetConcurrency) throws SQLException { + + if (setSelectMethod) { + conn = DriverManager.getConnection(connectionString + ";selectMethod=cursor;"); + } else { + conn = DriverManager.getConnection(connectionString); + } + + if (null != resultSetType || null != resultSetConcurrency) { + stmt = conn.createStatement(resultSetType, resultSetConcurrency); + } else { + stmt = conn.createStatement(); + } Utils.dropProcedureIfExists(procedureName, stmt); dropTVPS(tvpName); @@ -199,12 +188,16 @@ private void setupVariation() throws SQLException { } private void terminateVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - Utils.dropProcedureIfExists(procedureName, stmt); Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); dropTVPS(tvpName); + + if (null != stmt) { + stmt.close(); + } + if (null != conn) { + conn.close(); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java index 87ed449a3..5b128ec39 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java @@ -46,19 +46,19 @@ public class TVPIssuesTest extends AbstractTest { @Test public void tryTVPRSvarcharMax4000Issue() throws Exception { - setup(); - SQLServerStatement st = (SQLServerStatement) connection.createStatement(); - ResultSet rs = st.executeQuery("select * from " + srcTable_varcharMax); + try (SQLServerStatement st = (SQLServerStatement) connection.createStatement(); + ResultSet rs = st.executeQuery("select * from " + srcTable_varcharMax); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + desTable_varcharMax + " select * from ? ;"); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + desTable_varcharMax + " select * from ? ;")) { - pstmt.setStructured(1, tvp_varcharMax, rs); - pstmt.execute(); + pstmt.setStructured(1, tvp_varcharMax, rs); + pstmt.execute(); - testCharDestTable(); + testCharDestTable(); + } } /** @@ -74,8 +74,8 @@ public void testExceptionWithInvalidStoredProcedureName() throws Exception { dropProcedure(); final String sql = "{call " + spName_varcharMax + "(?)}"; - SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) connection.prepareCall(sql); - try { + + try (SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) connection.prepareCall(sql)) { Cstmt.setObject(1, rs); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { @@ -96,42 +96,36 @@ public void testExceptionWithInvalidStoredProcedureName() throws Exception { */ @Test public void tryTVPPrecisionmissedissue315() throws Exception { - setup(); - ResultSet rs = stmt.executeQuery("select * from " + srcTable_time_6); + try (ResultSet rs = stmt.executeQuery("select * from " + srcTable_time_6); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + desTable_time_6 + " select * from ? ;")) { + pstmt.setStructured(1, tvp_time_6, rs); + pstmt.execute(); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + desTable_time_6 + " select * from ? ;"); - pstmt.setStructured(1, tvp_time_6, rs); - pstmt.execute(); - - testTime6DestTable(); + testTime6DestTable(); + } } private void testCharDestTable() throws SQLException, IOException { - ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_varcharMax); - while (rs.next()) { - assertEquals(rs.getString(1).length(), 4001, TestResource.getResource("R_lengthTruncated")); - } - if (null != rs) { - rs.close(); + try (ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_varcharMax)) { + while (rs.next()) { + assertEquals(rs.getString(1).length(), 4001, TestResource.getResource("R_lengthTruncated")); + } } } private void testTime6DestTable() throws SQLException, IOException { - ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_time_6); - while (rs.next()) { - assertEquals(rs.getString(1), expectedTime6value, TestResource.getResource("R_timeValueTruncated")); - } - if (null != rs) { - rs.close(); + try (ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_time_6)) { + while (rs.next()) { + assertEquals(rs.getString(1), expectedTime6value, TestResource.getResource("R_timeValueTruncated")); + } } } @BeforeAll public static void beforeAll() throws SQLException { - connection = DriverManager.getConnection(connectionString); stmt = connection.createStatement(); @@ -166,7 +160,7 @@ public static void beforeAll() throws SQLException { createPreocedure(); populateCharSrcTable(); - populateTime6SrcTable(); + populateTime6SrcTable(); } private static void populateCharSrcTable() throws SQLException { @@ -178,10 +172,11 @@ private static void populateCharSrcTable() throws SQLException { } String value = sb.toString(); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { - pstmt.setString(1, value); - pstmt.execute(); + pstmt.setString(1, value); + pstmt.execute(); + } } private static void populateTime6SrcTable() throws SQLException { @@ -213,11 +208,12 @@ public static void terminateVariation() throws SQLException { Utils.dropTableIfExists(srcTable_time_6, stmt); Utils.dropTableIfExists(desTable_time_6, stmt); - if (null != connection) { - connection.close(); - } if (null != stmt) { stmt.close(); } + + if (null != connection) { + connection.close(); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java index 98a989cc9..1cfbeedc9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java @@ -49,14 +49,11 @@ public void testNumericPresicionIssue211() throws SQLException { tvp.addRow(12.12); tvp.addRow(1.123); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + charTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + charTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - - if (null != pstmt) { - pstmt.close(); + pstmt.execute(); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java index 88ce22dcc..d8104c130 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java @@ -76,21 +76,14 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro populateSourceTable(); - ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency) + try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency) .executeQuery("select * from " + srcTable); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, rs); - pstmt.execute(); - - verifyDestinationTableData(expectedBigDecimals.length); - - if (null != pstmt) { - pstmt.close(); - } - if (null != rs) { - rs.close(); + verifyDestinationTableData(expectedBigDecimals.length); } } @@ -116,20 +109,13 @@ public void testSelectMethodSetToCursor() throws SQLException { populateSourceTable(); - ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, rs); - pstmt.execute(); - - verifyDestinationTableData(expectedBigDecimals.length); + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); - if (null != pstmt) { - pstmt.close(); - } - if (null != rs) { - rs.close(); + verifyDestinationTableData(expectedBigDecimals.length); } } @@ -157,24 +143,15 @@ public void testSelectMethodSetToCursorWithSP() throws SQLException { populateSourceTable(); - ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn + .prepareCall("{call " + procedureName + "(?)}")) { + pstmt.setStructured(1, tvpName, rs); - final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn.prepareCall(sql); - pstmt.setStructured(1, tvpName, rs); - - try { pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length); } finally { - if (null != pstmt) { - pstmt.close(); - } - if (null != rs) { - rs.close(); - } - dropProcedure(); } } @@ -200,25 +177,17 @@ public void testInvalidTVPName() throws SQLException { populateSourceTable(); - ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt.setStructured(1, "invalid" + tvpName, rs); + pstmt.setStructured(1, "invalid" + tvpName, rs); - try { pstmt.execute(); } catch (SQLException e) { if (!e.getMessage().contains(TestResource.getResource("R_dataTypeNotFound"))) { throw e; } - } finally { - if (null != pstmt) { - pstmt.close(); - } - if (null != rs) { - rs.close(); - } } } @@ -245,13 +214,11 @@ public void testInvalidStoredProcedureName() throws SQLException { populateSourceTable(); - ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - - final String sql = "{call invalid" + procedureName + "(?)}"; - SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn.prepareCall(sql); - pstmt.setStructured(1, tvpName, rs); + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn + .prepareCall("{call invalid" + procedureName + "(?)}")) { + pstmt.setStructured(1, tvpName, rs); - try { pstmt.execute(); } catch (SQLException e) { if (!e.getMessage().contains(TestResource.getResource("R_StoredProcedureNotFound"))) { @@ -259,13 +226,6 @@ public void testInvalidStoredProcedureName() throws SQLException { } } finally { - if (null != pstmt) { - pstmt.close(); - } - if (null != rs) { - rs.close(); - } - dropProcedure(); } } @@ -289,81 +249,94 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { populateSourceTable(); - ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) - .executeQuery("select * from " + srcTable); + ResultSet rs = null; + ResultSet rs2 = null; + SQLServerPreparedStatement pstmt1 = null; + SQLServerPreparedStatement pstmt2 = null; - SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt1.setStructured(1, tvpName, rs); - pstmt1.execute(); - verifyDestinationTableData(expectedBigDecimals.length); - - rs.beforeFirst(); - pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt1.setStructured(1, tvpName, rs); - pstmt1.execute(); - verifyDestinationTableData(expectedBigDecimals.length * 2); - - rs.beforeFirst(); - SQLServerPreparedStatement pstmt2 = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt2.setStructured(1, tvpName, rs); - pstmt2.execute(); - verifyDestinationTableData(expectedBigDecimals.length * 3); - - String sql = "insert into " + desTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - 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]); + try { + + rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) + .executeQuery("select * from " + srcTable); + + pstmt1 = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); + pstmt1.setStructured(1, tvpName, rs); pstmt1.execute(); - } - verifyDestinationTableData(expectedBigDecimals.length * 4); + verifyDestinationTableData(expectedBigDecimals.length); - ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) - .executeQuery("select * from " + srcTable); + rs.beforeFirst(); + pstmt1 = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); + pstmt1.setStructured(1, tvpName, rs); + pstmt1.execute(); + verifyDestinationTableData(expectedBigDecimals.length * 2); + + rs.beforeFirst(); + pstmt2 = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); + pstmt2.setStructured(1, tvpName, rs); + pstmt2.execute(); + verifyDestinationTableData(expectedBigDecimals.length * 3); + + String sql = "insert into " + desTable + " values (?,?,?,?)"; + Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + 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); - pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt1.setStructured(1, tvpName, rs2); - pstmt1.execute(); - verifyDestinationTableData(expectedBigDecimals.length * 5); + rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) + .executeQuery("select * from " + srcTable); - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - if (null != rs) { - rs.close(); - } - if (null != rs2) { - rs2.close(); + pstmt1 = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); + pstmt1.setStructured(1, tvpName, rs2); + pstmt1.execute(); + verifyDestinationTableData(expectedBigDecimals.length * 5); + } finally { + + if (null != pstmt1) { + pstmt1.close(); + } + if (null != pstmt2) { + pstmt2.close(); + } + if (null != rs) { + rs.close(); + } + + if (null != rs2) { + rs2.close(); + } } } 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 (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 { @@ -371,14 +344,15 @@ private static void populateSourceTable() throws SQLException { Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql); + try (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(); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java index 7ec4a7776..4abf1bc12 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java @@ -52,15 +52,12 @@ public void testTVPSchemaPreparedStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - SQLServerPreparedStatement P_C_statement = (SQLServerPreparedStatement) connection.prepareStatement(sql); - P_C_statement.setStructured(1, tvpNameWithSchema, tvp); - P_C_statement.execute(); + try (SQLServerPreparedStatement P_C_statement = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { + P_C_statement.setStructured(1, tvpNameWithSchema, tvp); + P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + charTable); - verify(rs); - - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + charTable); + verify(rs); } } @@ -75,15 +72,12 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql); - P_C_statement.setStructured(1, tvpNameWithSchema, tvp); - P_C_statement.execute(); - - rs = stmt.executeQuery("select * from " + charTable); - verify(rs); + try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + P_C_statement.setStructured(1, tvpNameWithSchema, tvp); + P_C_statement.execute(); - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + charTable); + verify(rs); } } @@ -97,16 +91,13 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException @DisplayName("TVPSchemaPreparedInsertCommand") public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOException { - SQLServerPreparedStatement P_C_stmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + charTable + " select * from ? ;"); - P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); - P_C_stmt.executeUpdate(); + try (SQLServerPreparedStatement P_C_stmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + charTable + " select * from ? ;")) { + P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); + P_C_stmt.executeUpdate(); - rs = stmt.executeQuery("select * from " + charTable); - verify(rs); - - if (null != P_C_stmt) { - P_C_stmt.close(); + rs = stmt.executeQuery("select * from " + charTable); + verify(rs); } } @@ -120,16 +111,13 @@ public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOExceptio @DisplayName("TVPSchemaCallableInsertCommand()") public void testTVPSchemaCallableInsertCommand() throws SQLException, IOException { - SQLServerCallableStatement P_C_stmt = (SQLServerCallableStatement) connection - .prepareCall("INSERT INTO " + charTable + " select * from ? ;"); - P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); - P_C_stmt.executeUpdate(); - - rs = stmt.executeQuery("select * from " + charTable); - verify(rs); + try (SQLServerCallableStatement P_C_stmt = (SQLServerCallableStatement) connection + .prepareCall("INSERT INTO " + charTable + " select * from ? ;")) { + P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); + P_C_stmt.executeUpdate(); - if (null != P_C_stmt) { - P_C_stmt.close(); + rs = stmt.executeQuery("select * from " + charTable); + verify(rs); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java index 4ec14f92a..a187fd64f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java @@ -59,18 +59,16 @@ public void testLongVarchar() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); + pstmt.execute(); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(rs.getString(1), value); - } - if (null != pstmt) { - pstmt.close(); + rs = conn.createStatement().executeQuery("select * from " + table); + while (rs.next()) { + assertEquals(rs.getString(1), value); + } } } @@ -93,19 +91,16 @@ public void testLongNVarchar() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - - pstmt.execute(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(rs.getString(1), value); - } + pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + rs = conn.createStatement().executeQuery("select * from " + table); + while (rs.next()) { + assertEquals(rs.getString(1), value); + } } } @@ -126,19 +121,16 @@ public void testXML() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.SQLXML); tvp.addRow(value); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - - pstmt.execute(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - Connection con = DriverManager.getConnection(connectionString); - ResultSet rs = con.createStatement().executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + Connection con = DriverManager.getConnection(connectionString); + ResultSet rs = con.createStatement().executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -159,19 +151,16 @@ public void testnText() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - - pstmt.execute(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - Connection con = DriverManager.getConnection(connectionString); - ResultSet rs = con.createStatement().executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + Connection con = DriverManager.getConnection(connectionString); + ResultSet rs = con.createStatement().executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -192,19 +181,16 @@ public void testText() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - - Connection con = DriverManager.getConnection(connectionString); - ResultSet rs = con.createStatement().executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + Connection con = DriverManager.getConnection(connectionString); + ResultSet rs = con.createStatement().executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -264,16 +250,13 @@ public void testTVPLongVarcharStoredProcedure() throws SQLException { final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql); - P_C_statement.setStructured(1, tvpName, tvp); - P_C_statement.execute(); - - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + P_C_statement.setStructured(1, tvpName, tvp); + P_C_statement.execute(); - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -298,16 +281,13 @@ public void testTVPLongNVarcharStoredProcedure() throws SQLException { final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql); - P_C_statement.setStructured(1, tvpName, tvp); - P_C_statement.execute(); + try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + P_C_statement.setStructured(1, tvpName, tvp); + P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); - - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -332,15 +312,13 @@ public void testTVPXMLStoredProcedure() throws SQLException { final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql); - P_C_statement.setStructured(1, tvpName, tvp); - P_C_statement.execute(); + try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + P_C_statement.setStructured(1, tvpName, tvp); + P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -366,15 +344,13 @@ public void testTVPTextStoredProcedure() throws SQLException { final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql); - P_C_statement.setStructured(1, tvpName, tvp); - P_C_statement.execute(); + try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + P_C_statement.setStructured(1, tvpName, tvp); + P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -400,15 +376,13 @@ public void testTVPNTextStoredProcedure() throws SQLException { final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql); - P_C_statement.setStructured(1, tvpName, tvp); - P_C_statement.execute(); + try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + P_C_statement.setStructured(1, tvpName, tvp); + P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + table); + while (rs.next()) + assertEquals(rs.getString(1), value); } } @@ -434,15 +408,13 @@ public void testTVPImageStoredProcedure() throws SQLException { final String sql = "{call " + procedureName + "(?)}"; - SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql); - P_C_statement.setStructured(1, tvpName, tvp); - P_C_statement.execute(); + try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + P_C_statement.setStructured(1, tvpName, tvp); + P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertTrue(parseByte(rs.getBytes(1), value.getBytes())); - if (null != P_C_statement) { - P_C_statement.close(); + rs = stmt.executeQuery("select * from " + table); + while (rs.next()) + assertTrue(parseByte(rs.getBytes(1), value.getBytes())); } } @@ -462,18 +434,16 @@ public void testDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.DATETIME); tvp.addRow(value); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); + pstmt.execute(); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(((SQLServerResultSet) rs).getDateTime(1), value); - } - if (null != pstmt) { - pstmt.close(); + rs = conn.createStatement().executeQuery("select * from " + table); + while (rs.next()) { + assertEquals(((SQLServerResultSet) rs).getDateTime(1), value); + } } } @@ -494,18 +464,16 @@ public void testSmallDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SMALLDATETIME); tvp.addRow(value); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); + pstmt.execute(); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(((SQLServerResultSet) rs).getSmallDateTime(1), returnValue); - } - if (null != pstmt) { - pstmt.close(); + rs = conn.createStatement().executeQuery("select * from " + table); + while (rs.next()) { + assertEquals(((SQLServerResultSet) rs).getSmallDateTime(1), returnValue); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java index 5dea7bf79..7a44ea701 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java @@ -11,7 +11,6 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; -import java.sql.Statement; import java.text.MessageFormat; import org.junit.jupiter.api.Test; @@ -30,8 +29,6 @@ @RunWith(JUnitPlatform.class) public class TestSavepoint extends AbstractTest { - Connection connection = null; - Statement statement = null; String savePointName = RandomUtil.getIdentifier("SavePoint", 31, true, false); /** @@ -39,24 +36,26 @@ public class TestSavepoint extends AbstractTest { */ @Test public void testSavePointName() throws SQLException { - connection = DriverManager.getConnection(connectionString); + try (Connection connection = DriverManager.getConnection(connectionString)) { - connection.setAutoCommit(false); + connection.setAutoCommit(false); - SQLServerSavepoint savePoint = (SQLServerSavepoint) connection.setSavepoint(savePointName); - MessageFormat form = new MessageFormat(TestResource.getResource("R_savePointError")); - Object[][] msgArgs = {{"Name", "same"}, {"Label", "Savepoint Name"}, {"SQLServerSavepoint.isNamed", "true"}}; + SQLServerSavepoint savePoint = (SQLServerSavepoint) connection.setSavepoint(savePointName); + MessageFormat form = new MessageFormat(TestResource.getResource("R_savePointError")); + Object[][] msgArgs = {{"Name", "same"}, {"Label", "Savepoint Name"}, + {"SQLServerSavepoint.isNamed", "true"}}; - assertTrue(savePointName.equals(savePoint.getSavepointName()), form.format(msgArgs[0])); - assertTrue(savePointName.equals(savePoint.getLabel()), form.format(msgArgs[1])); - assertTrue(savePoint.isNamed(), form.format(msgArgs[2])); + assertTrue(savePointName.equals(savePoint.getSavepointName()), form.format(msgArgs[0])); + assertTrue(savePointName.equals(savePoint.getLabel()), form.format(msgArgs[1])); + assertTrue(savePoint.isNamed(), form.format(msgArgs[2])); - try { - savePoint.getSavepointId(); - assertTrue(false, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) {} + try { + savePoint.getSavepointId(); + assertTrue(false, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) {} - connection.rollback(); + connection.rollback(); + } } /** @@ -66,25 +65,26 @@ public void testSavePointName() throws SQLException { */ @Test public void testSavePointId() throws SQLException { - connection = DriverManager.getConnection(connectionString); + try (Connection connection = DriverManager.getConnection(connectionString)) { - connection.setAutoCommit(false); + connection.setAutoCommit(false); - SQLServerSavepoint savePoint = (SQLServerSavepoint) connection.setSavepoint(null); + SQLServerSavepoint savePoint = (SQLServerSavepoint) connection.setSavepoint(null); - MessageFormat form = new MessageFormat(TestResource.getResource("R_savePointError")); - Object[][] msgArgs = {{"label", "not null"}, {"id", "not 0"}}; - assertNotNull(savePoint.getLabel(), form.format(msgArgs[0])); + MessageFormat form = new MessageFormat(TestResource.getResource("R_savePointError")); + Object[][] msgArgs = {{"label", "not null"}, {"id", "not 0"}}; + assertNotNull(savePoint.getLabel(), form.format(msgArgs[0])); - try { + try { - savePoint.getSavepointName(); - // Expecting Exception as trying to get SavePointname when we created savepoint without name - assertTrue(false, TestResource.getResource("R_shouldThrowException")); - } catch (SQLException e) {} + savePoint.getSavepointName(); + // Expecting Exception as trying to get SavePointname when we created savepoint without name + assertTrue(false, TestResource.getResource("R_shouldThrowException")); + } catch (SQLException e) {} - assertTrue(savePoint.getSavepointId() != 0, form.format(msgArgs[1])); - connection.rollback(); + assertTrue(savePoint.getSavepointId() != 0, form.format(msgArgs[1])); + connection.rollback(); + } } /** @@ -94,16 +94,17 @@ public void testSavePointId() throws SQLException { */ @Test public void testSavePointIsNamed() throws SQLException { - connection = DriverManager.getConnection(connectionString); + try (Connection connection = DriverManager.getConnection(connectionString)) { - connection.setAutoCommit(false); + connection.setAutoCommit(false); - SQLServerSavepoint savePoint = (SQLServerSavepoint) connection.setSavepoint(null); + SQLServerSavepoint savePoint = (SQLServerSavepoint) connection.setSavepoint(null); - // SQLServerSavepoint.isNamed should be false as savePoint is created without name" - assertFalse(savePoint.isNamed(), TestResource.getResource("R_shouldThrowException")); + // SQLServerSavepoint.isNamed should be false as savePoint is created without name" + assertFalse(savePoint.isNamed(), TestResource.getResource("R_shouldThrowException")); - connection.rollback(); + connection.rollback(); + } } /** @@ -113,16 +114,15 @@ public void testSavePointIsNamed() throws SQLException { */ @Test public void testSavePointWithAutoCommit() throws SQLException { - connection = DriverManager.getConnection(connectionString); + try (Connection connection = DriverManager.getConnection(connectionString)) { - connection.setAutoCommit(true); - - try { - connection.setSavepoint(null); - // Expecting Exception as can not set SetPoint when AutoCommit mode is set to true - assertTrue(false, TestResource.getResource("R_shouldThrowException")); - } catch (SQLException e) {} + connection.setAutoCommit(true); + try { + connection.setSavepoint(null); + // Expecting Exception as can not set SetPoint when AutoCommit mode is set to true + assertTrue(false, TestResource.getResource("R_shouldThrowException")); + } catch (SQLException e) {} + } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java index 45be57ee6..3c2262214 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java @@ -118,10 +118,14 @@ public static void setUp() throws ClassNotFoundException, SQLException { @AfterAll public static void cleanUp() throws SQLException { - if (Utils.serverSupportsUTF8(connection)) { - Utils.dropDatabaseIfExists(databaseName, connection.createStatement()); + try (Statement stmt = connection.createStatement()) { + if (Utils.serverSupportsUTF8(connection)) { + Utils.dropDatabaseIfExists(databaseName, stmt); + } + } + if (null != connection) { + connection.close(); } - connection.close(); } private static void createDatabaseWithUTF8Collation() throws SQLException { @@ -145,6 +149,7 @@ public void clearTable() throws SQLException { } public void validate(String value) throws SQLException { + ResultSet rs = null; try (PreparedStatement psInsert = connection.prepareStatement("INSERT INTO " + tableName + " VALUES(?)"); PreparedStatement psFetch = connection.prepareStatement("SELECT * FROM " + tableName); Statement stmt = connection.createStatement();) { @@ -156,18 +161,23 @@ public void validate(String value) throws SQLException { psInsert.executeUpdate(); // Fetch using Statement. - ResultSet rsStatement = stmt.executeQuery("SELECT * FROM " + tableName); - rsStatement.next(); + rs = stmt.executeQuery("SELECT * FROM " + tableName); + rs.next(); // Compare Strings. - assertEquals(value, rsStatement.getString(1)); + assertEquals(value, rs.getString(1)); // Test UTF8 sequence returned from getBytes(). - assertArrayEquals(valueBytes, rsStatement.getBytes(1)); + assertArrayEquals(valueBytes, rs.getBytes(1)); // Fetch using PreparedStatement. - ResultSet rsPreparedStatement = psFetch.executeQuery(); - rsPreparedStatement.next(); - assertEquals(value, rsPreparedStatement.getString(1)); - assertArrayEquals(valueBytes, rsPreparedStatement.getBytes(1)); + try (ResultSet rsPreparedStatement = psFetch.executeQuery()) { + rsPreparedStatement.next(); + assertEquals(value, rsPreparedStatement.getString(1)); + assertArrayEquals(valueBytes, rsPreparedStatement.getBytes(1)); + } + } finally { + if (null != rs) { + rs.close(); + } } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java index ed4755488..f1d34acf2 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java @@ -146,24 +146,27 @@ private void testInvalidLobs(Class lobClass, boolean isResultSet) throws SQLExce } int coercionType = isResultSet ? DBCoercion.UPDATE : DBCoercion.SET; + Object updater = null; + Statement stmt = null; try { if (clobType == classType(lobClass) || nClobType == classType(lobClass)) { - table = this.createTable(table, clobTypes, true); + table = createTable(table, clobTypes, true); } else { - table = this.createTable(table, blobTypes, true); + table = createTable(table, blobTypes, true); } - Object updater; for (int i = 0; i < table.getColumns().size(); i++) { DBColumn col = table.getColumns().get(i); - if (!col.getSqlType().canConvert(lobClass, coercionType, new DBConnection(connectionString))) + try (DBConnection conn = new DBConnection(connectionString)) { + if (!col.getSqlType().canConvert(lobClass, coercionType, conn)) continue; + } // re-create LOB since it might get closed Object lob = this.createLob(lobClass); if (isResultSet) { - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - updater = stmt.executeQuery("Select " + table.getEscapedTableName() + ".[" + col.getColumnName() - + "]" + " from " + table.getEscapedTableName()); - ((ResultSet) updater).next(); + stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + updater = stmt.executeQuery("Select " + table.getEscapedTableName() + ".[" + col.getColumnName() + + "]" + " from " + table.getEscapedTableName()); + ((ResultSet) updater).next(); } else updater = conn.prepareStatement("update " + table.getEscapedTableName() + " set " + ".[" + col.getColumnName() + "]" + "=?"); @@ -191,15 +194,15 @@ else if (lobClass == Blob.class) // Case 2: CharacterStream or Clob.getCharacterStream threw IOException if (lobClass == DBCharacterStream.class || (lobClass == Clob.class && ((DBInvalidUtil.InvalidClob) lob).stream != null)) { - DBInvalidUtil.InvalidCharacterStream stream = lobClass == DBCharacterStream.class ? ((DBInvalidUtil.InvalidCharacterStream) lob) - : ((DBInvalidUtil.InvalidClob) lob).stream; + try (DBInvalidUtil.InvalidCharacterStream stream = lobClass == DBCharacterStream.class ? ((DBInvalidUtil.InvalidCharacterStream) lob) + : ((DBInvalidUtil.InvalidClob) lob).stream) { if (stream.threwException) { // CharacterStream threw IOException String[] args = { "java.io.IOException: " + DBInvalidUtil.InvalidCharacterStream.IOExceptionMsg}; assertTrue(e.getMessage().contains(args[0])); verified = true; - + } } } if (!verified) { @@ -216,8 +219,20 @@ else if (lobClass == Blob.class) } } } catch (Exception e) { - this.dropTables(table); + dropTables(table); e.printStackTrace(); + } finally { + dropTables(table); + if (null != updater) { + if (isResultSet) { + ((ResultSet) updater).close(); + } else { + ((PreparedStatement) updater).close(); + } + } + if (null != stmt) { + stmt.close(); + } } } @@ -235,41 +250,44 @@ private void testFreedBlobs(Class lobClass, boolean isResultSet) throws SQLExcep Blob blob = null; InputStream stream = null; for (int i = 0; i < 5; i++) { - PreparedStatement ps = conn - .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)"); - blob = conn.createBlob(); - blob.setBytes(1, data); - ps.setInt(1, i + 1); - ps.setBlob(2, blob); - ps.executeUpdate(); + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + blob = conn.createBlob(); + blob.setBytes(1, data); + ps.setInt(1, i + 1); + ps.setBlob(2, blob); + ps.executeUpdate(); + } } - byte[] chunk = new byte[size]; - ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName()); - for (int i = 0; i < 5; i++) { - rs.next(); + try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { + for (int i = 0; i < 5; i++) { + rs.next(); - blob = rs.getBlob(2); - stream = blob.getBinaryStream(); - while (stream.available() > 0) - stream.read(); - blob.free(); - try { + blob = rs.getBlob(2); stream = blob.getBinaryStream(); - } catch (SQLException e) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); + while (stream.available() > 0) + stream.read(); + blob.free(); + try { + stream = blob.getBinaryStream(); + } catch (SQLException e) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); + } } } - rs.close(); try { stream = blob.getBinaryStream(); } catch (SQLException e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); } } catch (Exception e) { - this.dropTables(table); + dropTables(table); e.printStackTrace(); } + finally { + dropTables(table); + } } @Test @@ -291,85 +309,85 @@ public void MultipleCloseBinaryStream() throws Exception { * @throws Exception */ private void testMultipleClose(Class streamClass) throws Exception { - DBConnection conn = new DBConnection(connectionString); String[] types = {"varchar(max)", "nvarchar(max)", "varbinary(max)"}; - try { - table = this.createTable(table, types, true); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { + table = createTable(table, types, true); - DBStatement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); String query = "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0); - DBResultSet rs = stmt.executeQuery(query); - while (rs.next()) { - for (int i = 0; i < types.length + 1; i++) { // +1 for RowId - if (i == 0) { - rs.getInt(1); - } else { - DBColumn col = table.getColumns().get(i); - if (!col.getSqlType().canConvert(streamClass, DBCoercion.GET, - new DBConnection(connectionString))) - continue; - Object stream = rs.getXXX(i + 1, streamClass); - if (stream == null) { - assertEquals(stream, rs.getObject(i + 1), TestResource.getResource("R_streamNull")); + try (DBResultSet rs = stmt.executeQuery(query)) { + while (rs.next()) { + for (int i = 0; i < types.length + 1; i++) { // +1 for RowId + if (i == 0) { + rs.getInt(1); } else { - // close the stream twice - if (streamClass == DBCharacterStream.class) { - ((Reader) stream).close(); - ((Reader) stream).close(); + DBColumn col = table.getColumns().get(i); + try (DBConnection con = new DBConnection(connectionString)) { + if (!col.getSqlType().canConvert(streamClass, DBCoercion.GET, con)) + continue; + } + Object stream = rs.getXXX(i + 1, streamClass); + if (stream == null) { + assertEquals(stream, rs.getObject(i + 1), TestResource.getResource("R_streamNull")); } else { - ((InputStream) stream).close(); - ((InputStream) stream).close(); + // close the stream twice + if (streamClass == DBCharacterStream.class) { + ((Reader) stream).close(); + ((Reader) stream).close(); + } else { + ((InputStream) stream).close(); + ((InputStream) stream).close(); + } } } } } } } finally { - if (null != table) - this.dropTables(table); - if (null != null) - conn.close(); + if (null != table) { + dropTables(table); + } } } /** - * Tests Insert Retrive on nclob + * Tests Insert Retrieve on nclob * * @throws Exception */ @Test - @DisplayName("testlLobsInsertRetrive") + @DisplayName("testlLobsInsertRetrieve") public void testNClob() throws Exception { String types[] = {"nvarchar(max)"}; - testLobsInsertRetrive(types, NClob.class); + testLobsInsertRetrieve(types, NClob.class); } /** - * Tests Insert Retrive on blob + * Tests Insert Retrieve on blob * * @throws Exception */ @Test - @DisplayName("testlLobsInsertRetrive") + @DisplayName("testlLobsInsertRetrieve") public void testBlob() throws Exception { String types[] = {"varbinary(max)"}; - testLobsInsertRetrive(types, Blob.class); + testLobsInsertRetrieve(types, Blob.class); } /** - * Tests Insert Retrive on clob + * Tests Insert Retrieve on clob * * @throws Exception */ @Test - @DisplayName("testlLobsInsertRetrive") + @DisplayName("testlLobsInsertRetrieve") public void testClob() throws Exception { String types[] = {"varchar(max)"}; - testLobsInsertRetrive(types, Clob.class); + testLobsInsertRetrieve(types, Clob.class); } - private void testLobsInsertRetrive(String types[], Class lobClass) throws Exception { + private void testLobsInsertRetrieve(String types[], Class lobClass) throws Exception { table = createTable(table, types, false); // create empty table int size = 10000; @@ -380,70 +398,72 @@ private void testLobsInsertRetrive(String types[], Class lobClass) throws Except Blob blob = null; NClob nclob = null; InputStream stream = null; - PreparedStatement ps = conn.prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)"); - if (clobType == classType(lobClass)) { - String stringData = new String(data); - size = stringData.length(); - clob = conn.createClob(); - clob.setString(1, stringData); - ps.setInt(1, 1); - ps.setClob(2, clob); - } else if (nClobType == classType(lobClass)) { - String stringData = new String(data); - size = stringData.length(); - nclob = conn.createNClob(); - nclob.setString(1, stringData); - ps.setInt(1, 1); - ps.setNClob(2, nclob); - } - - else { - blob = conn.createBlob(); - blob.setBytes(1, data); - ps.setInt(1, 1); - ps.setBlob(2, blob); - } - ps.executeUpdate(); - - byte[] chunk = new byte[size]; - ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName()); - while (rs.next()) { + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { if (clobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); - rs.getClob(2); - stream = clob.getAsciiStream(); - assertEquals(clob.length(), size); - + ps.setInt(1, 1); + ps.setClob(2, clob); } else if (nClobType == classType(lobClass)) { - nclob = rs.getNClob(2); - assertEquals(nclob.length(), size); - stream = nclob.getAsciiStream(); - BufferedInputStream is = new BufferedInputStream(stream); - is.read(chunk); - assertEquals(chunk.length, size); - } else { - blob = rs.getBlob(2); - stream = blob.getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + String stringData = new String(data); + size = stringData.length(); + nclob = conn.createNClob(); + nclob.setString(1, stringData); + ps.setInt(1, 1); + ps.setNClob(2, nclob); + } + else { + blob = conn.createBlob(); + blob.setBytes(1, data); + ps.setInt(1, 1); + ps.setBlob(2, blob); } + ps.executeUpdate(); - } + byte[] chunk = new byte[size]; + try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { + while (rs.next()) { + if (clobType == classType(lobClass)) { + String stringData = new String(data); + size = stringData.length(); + clob = conn.createClob(); + clob.setString(1, stringData); + rs.getClob(2); + stream = clob.getAsciiStream(); + assertEquals(clob.length(), size); + + } else if (nClobType == classType(lobClass)) { + nclob = rs.getNClob(2); + assertEquals(nclob.length(), size); + stream = nclob.getAsciiStream(); + BufferedInputStream is = new BufferedInputStream(stream); + is.read(chunk); + assertEquals(chunk.length, size); + } else { + blob = rs.getBlob(2); + stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } + } - if (null != clob) - clob.free(); - if (null != blob) - blob.free(); - if (null != nclob) - nclob.free(); - dropTables(table); + } + } finally { + if (null != clob) + clob.free(); + if (null != blob) + blob.free(); + if (null != nclob) + nclob.free(); + dropTables(table); + } } @Test @@ -479,36 +499,39 @@ public void readBlobStreamAfterClosingRS() throws Exception { Blob blob = null; InputStream stream = null; - PreparedStatement ps = conn.prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)"); - blob = conn.createBlob(); - blob.setBytes(1, data); - ps.setInt(1, 1); - ps.setBlob(2, blob); - ps.executeUpdate(); + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + blob = conn.createBlob(); + blob.setBytes(1, data); + ps.setInt(1, 1); + ps.setBlob(2, blob); + ps.executeUpdate(); - byte[] chunk = new byte[size]; - ResultSet rs = stmt.executeQuery( - "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0)); - rs.next(); - - blob = rs.getBlob(2); - stream = blob.getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); - rs.close(); - stream = blob.getBinaryStream(); - buffer = new ByteArrayOutputStream(); - read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); - - if (null != blob) - blob.free(); - dropTables(table); + byte[] chunk = new byte[size]; + try (ResultSet rs = stmt.executeQuery( + "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0))) { + rs.next(); + + blob = rs.getBlob(2); + stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + rs.close(); + stream = blob.getBinaryStream(); + buffer = new ByteArrayOutputStream(); + read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } + } finally { + if (null != blob) + blob.free(); + dropTables(table); + } } @Test @@ -523,29 +546,31 @@ public void readMultipleBlobStreamsThenCloseRS() throws Exception { InputStream stream = null; for (int i = 0; i < 5; i++)// create 5 blobs { - PreparedStatement ps = conn - .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)"); - blobs[i] = conn.createBlob(); - ThreadLocalRandom.current().nextBytes(data); - blobs[i].setBytes(1, data); - ps.setInt(1, i + 1); - ps.setBlob(2, blobs[i]); - ps.executeUpdate(); + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + blobs[i] = conn.createBlob(); + ThreadLocalRandom.current().nextBytes(data); + blobs[i].setBytes(1, data); + ps.setInt(1, i + 1); + ps.setBlob(2, blobs[i]); + ps.executeUpdate(); + } } + byte[] chunk = new byte[size]; - ResultSet rs = stmt.executeQuery( - "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0)); - for (int i = 0; i < 5; i++) { - rs.next(); - blobs[i] = rs.getBlob(2); - stream = blobs[i].getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + try (ResultSet rs = stmt.executeQuery( + "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0))) { + for (int i = 0; i < 5; i++) { + rs.next(); + blobs[i] = rs.getBlob(2); + stream = blobs[i].getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } } - rs.close(); for (int i = 0; i < 5; i++) { stream = blobs[i].getBinaryStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); @@ -566,62 +591,64 @@ private void testUpdateLobs(String types[], Class lobClass) throws Exception { Clob clob = null; Blob blob = null; NClob nclob = null; - InputStream stream = null; - PreparedStatement ps = conn.prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)"); - if (clobType == classType(lobClass)) { - String stringData = new String(data); - size = stringData.length(); - clob = conn.createClob(); - clob.setString(1, stringData); - ps.setInt(1, 1); - ps.setClob(2, clob); - } else if (nClobType == classType(lobClass)) { - String stringData = new String(data); - size = stringData.length(); - nclob = conn.createNClob(); - nclob.setString(1, stringData); - ps.setInt(1, 1); - ps.setNClob(2, nclob); - } - - else { - blob = conn.createBlob(); - blob.setBytes(1, data); - ps.setInt(1, 1); - ps.setBlob(2, blob); - } - ps.executeUpdate(); - - Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName()); - while (rs.next()) { + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { if (clobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); - rs.updateClob(2, clob); + ps.setInt(1, 1); + ps.setClob(2, clob); } else if (nClobType == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); nclob = conn.createNClob(); nclob.setString(1, stringData); - rs.updateClob(2, nclob); - } else { + ps.setInt(1, 1); + ps.setNClob(2, nclob); + } + + else { blob = conn.createBlob(); - rs.updateBlob(2, blob); + blob.setBytes(1, data); + ps.setInt(1, 1); + ps.setBlob(2, blob); + } + ps.executeUpdate(); + + try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { + while (rs.next()) { + if (clobType == classType(lobClass)) { + String stringData = new String(data); + size = stringData.length(); + clob = conn.createClob(); + clob.setString(1, stringData); + rs.updateClob(2, clob); + } else if (nClobType == classType(lobClass)) { + String stringData = new String(data); + size = stringData.length(); + nclob = conn.createNClob(); + nclob.setString(1, stringData); + rs.updateClob(2, nclob); + } else { + blob = conn.createBlob(); + rs.updateBlob(2, blob); + } + rs.updateRow(); + } } - rs.updateRow(); + } finally { + if (null != clob) + clob.free(); + if (null != blob) + blob.free(); + if (null != nclob) + nclob.free(); + dropTables(table); } - if (null != clob) - clob.free(); - if (null != blob) - blob.free(); - if (null != nclob) - nclob.free(); - dropTables(table); - } private int classType(Class type) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java index ae9c2e8ba..6371383d6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java @@ -96,28 +96,31 @@ private void Repro47239Internal(String mode) throws Exception { String warning; String error; String severe; - con = DriverManager.getConnection(connectionString); - if (DBConnection.isSqlAzure(con)) { - // SQL Azure will throw exception for "raiserror WITH LOG", so the following RAISERROR statements have not - // "with log" option - warning = "RAISERROR ('raiserror level 4',4,1)"; - error = "RAISERROR ('raiserror level 11',11,1)"; - // On SQL Azure, raising FATAL error by RAISERROR() is not supported and there is no way to - // cut the current connection by a statement inside a SQL batch. - // Details: Although one can simulate a fatal error (that cuts the connections) by dropping the database, - // this simulation cannot be written entirely in TSQL (because it needs a new connection), - // and thus it cannot be put into a TSQL batch and it is useless here. - // So we have to skip the last scenario of this test case, i.e. "Test Severe (connection-closing) errors" - // It is worthwhile to still execute the first 5 test scenarios of this test case, in order to have best - // test coverage. - severe = "--Not executed when testing against SQL Azure"; // this is a dummy statement that never being - // executed on SQL Azure - } else { - warning = "RAISERROR ('raiserror level 4',4,1) WITH LOG"; - error = "RAISERROR ('raiserror level 11',11,1) WITH LOG"; - severe = "RAISERROR ('raiserror level 20',20,1) WITH LOG"; + try (Connection con = DriverManager.getConnection(connectionString)) { + if (DBConnection.isSqlAzure(con)) { + // SQL Azure will throw exception for "raiserror WITH LOG", so the following RAISERROR statements have + // not + // "with log" option + warning = "RAISERROR ('raiserror level 4',4,1)"; + error = "RAISERROR ('raiserror level 11',11,1)"; + // On SQL Azure, raising FATAL error by RAISERROR() is not supported and there is no way to + // cut the current connection by a statement inside a SQL batch. + // Details: Although one can simulate a fatal error (that cuts the connections) by dropping the + // database, + // this simulation cannot be written entirely in TSQL (because it needs a new connection), + // and thus it cannot be put into a TSQL batch and it is useless here. + // So we have to skip the last scenario of this test case, i.e. "Test Severe (connection-closing) + // errors" + // It is worthwhile to still execute the first 5 test scenarios of this test case, in order to have best + // test coverage. + severe = "--Not executed when testing against SQL Azure"; // this is a dummy statement that never being + // executed on SQL Azure + } else { + warning = "RAISERROR ('raiserror level 4',4,1) WITH LOG"; + error = "RAISERROR ('raiserror level 11',11,1) WITH LOG"; + severe = "RAISERROR ('raiserror level 20',20,1) WITH LOG"; + } } - con.close(); int[] actualUpdateCounts; int[] expectedUpdateCounts; @@ -143,24 +146,25 @@ private void Repro47239Internal(String mode) throws Exception { // Regular Statement batch update expectedUpdateCounts = new int[] {1, -2, 1, -2, 1, -2}; - Statement batchStmt = conn.createStatement(); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - try { - actualUpdateCounts = batchStmt.executeBatch(); - actualExceptionText = ""; - } catch (BatchUpdateException bue) { - actualUpdateCounts = bue.getUpdateCounts(); - actualExceptionText = bue.getMessage(); - if (log.isLoggable(Level.FINE)) { - log.fine("BatchUpdateException occurred. Message:" + actualExceptionText); + try (Statement batchStmt = conn.createStatement()) { + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + try { + actualUpdateCounts = batchStmt.executeBatch(); + actualExceptionText = ""; + } catch (BatchUpdateException bue) { + actualUpdateCounts = bue.getUpdateCounts(); + actualExceptionText = bue.getMessage(); + if (log.isLoggable(Level.FINE)) { + log.fine("BatchUpdateException occurred. Message:" + actualExceptionText); + } + } finally { + batchStmt.close(); } - } finally { - batchStmt.close(); } if (log.isLoggable(Level.FINE)) { log.fine("UpdateCounts:"); @@ -291,12 +295,13 @@ private void Repro47239Internal(String mode) throws Exception { } } } - - try { - stmt.executeUpdate("drop table " + tableName); - } catch (Exception ignored) {} } - + } + finally { + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + stmt.executeUpdate("drop table " + tableName); + } } } @@ -353,23 +358,23 @@ private void Repro47239largeInternal(String mode) throws Exception { } catch (Exception ignored) {} // Regular Statement batch update expectedUpdateCounts = new long[] {1, -2, 1, -2, 1, -2}; - Statement batchStmt = conn.createStatement(); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - try { - actualUpdateCounts = batchStmt.executeLargeBatch(); - actualExceptionText = ""; - } catch (BatchUpdateException bue) { - actualUpdateCounts = bue.getLargeUpdateCounts(); - actualExceptionText = bue.getMessage(); - log.fine("BatchUpdateException occurred. Message:" + actualExceptionText); - } finally { - batchStmt.close(); + try (Statement batchStmt = conn.createStatement()) { + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + try { + actualUpdateCounts = batchStmt.executeLargeBatch(); + actualExceptionText = ""; + } catch (BatchUpdateException bue) { + actualUpdateCounts = bue.getLargeUpdateCounts(); + actualExceptionText = bue.getMessage(); + log.fine("BatchUpdateException occurred. Message:" + actualExceptionText); + } } + log.fine("UpdateCounts:"); for (long updateCount : actualUpdateCounts) { log.fine("" + updateCount + ","); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java index d572b62ca..9f9ee64c9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java @@ -38,12 +38,6 @@ @RunWith(JUnitPlatform.class) public class BatchExecutionTest extends AbstractTest { - static Statement stmt = null; - static Connection connection = null; - static PreparedStatement pstmt = null; - static PreparedStatement pstmt1 = null; - static ResultSet rs = null; - /** * testAddBatch1 and testExecutionBatch one looks similar except for the parameters being passed for select query. * TODO: we should look and simply the test later by parameterized values @@ -94,39 +88,39 @@ private void testExecuteBatch1Internal(String mode) { modifyConnectionForBulkCopyAPI((SQLServerConnection) connection); } - pstmt = connection.prepareStatement(sPrepStmt); - pstmt.setInt(1, 1); - pstmt.addBatch(); - - pstmt.setInt(1, 2); - pstmt.addBatch(); - - pstmt.setInt(1, 3); - pstmt.addBatch(); + try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { + pstmt.setInt(1, 1); + pstmt.addBatch(); - int[] updateCount = pstmt.executeBatch(); - updateCountlen = updateCount.length; + pstmt.setInt(1, 2); + pstmt.addBatch(); - assertTrue(updateCountlen == 3, TestResource.getResource("R_executeBatchFailed") + ": " - + TestResource.getResource("R_incorrectUpdateCount")); + pstmt.setInt(1, 3); + pstmt.addBatch(); - String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; + int[] updateCount = pstmt.executeBatch(); + updateCountlen = updateCount.length; - pstmt1 = connection.prepareStatement(sPrepStmt1); + assertTrue(updateCountlen == 3, TestResource.getResource("R_executeBatchFailed") + ": " + + TestResource.getResource("R_incorrectUpdateCount")); - for (int n = 1; n <= 3; n++) { - pstmt1.setInt(1, n); - rs = pstmt1.executeQuery(); - rs.next(); - retValue[i++] = rs.getInt(1); - } + String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; - pstmt1.close(); + try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1)) { + for (int n = 1; n <= 3; n++) { + pstmt1.setInt(1, n); + try (ResultSet rs = pstmt1.executeQuery()) { + rs.next(); + retValue[i++] = rs.getInt(1); + } + } + } - for (int j = 0; j < updateCount.length; j++) { - if (updateCount[j] != retValue[j] && updateCount[j] != Statement.SUCCESS_NO_INFO) { - fail(TestResource.getResource("R_executeBatchFailed") + ": " - + TestResource.getResource("R_incorrectUpdateCount")); + for (int j = 0; j < updateCount.length; j++) { + if (updateCount[j] != retValue[j] && updateCount[j] != Statement.SUCCESS_NO_INFO) { + fail(TestResource.getResource("R_executeBatchFailed") + ": " + + TestResource.getResource("R_incorrectUpdateCount")); + } } } } catch (Exception e) { @@ -135,25 +129,28 @@ private void testExecuteBatch1Internal(String mode) { } private static void createTable() throws SQLException { - String sql1 = "create table ctstable1 (TYPE_ID int, TYPE_DESC varchar(32), primary key(TYPE_ID)) "; - String sql2 = "create table ctstable2 (KEY_ID int, COF_NAME varchar(32), PRICE float, TYPE_ID int, primary key(KEY_ID), foreign key(TYPE_ID) references ctstable1) "; - stmt.execute(sql1); - stmt.execute(sql2); - - String sqlin2 = "insert into ctstable1 values (1,'COFFEE-Desc')"; - stmt.execute(sqlin2); - sqlin2 = "insert into ctstable1 values (2,'COFFEE-Desc2')"; - stmt.execute(sqlin2); - sqlin2 = "insert into ctstable1 values (3,'COFFEE-Desc3')"; - stmt.execute(sqlin2); - - String sqlin1 = "insert into ctstable2 values (9,'COFFEE-9',9.0, 1)"; - stmt.execute(sqlin1); - sqlin1 = "insert into ctstable2 values (10,'COFFEE-10',10.0, 2)"; - stmt.execute(sqlin1); - sqlin1 = "insert into ctstable2 values (11,'COFFEE-11',11.0, 3)"; - stmt.execute(sqlin1); - + try (Connection connection = DriverManager + .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); + Statement stmt = (SQLServerStatement) connection.createStatement()) { + String sql1 = "create table ctstable1 (TYPE_ID int, TYPE_DESC varchar(32), primary key(TYPE_ID)) "; + String sql2 = "create table ctstable2 (KEY_ID int, COF_NAME varchar(32), PRICE float, TYPE_ID int, primary key(KEY_ID), foreign key(TYPE_ID) references ctstable1) "; + stmt.execute(sql1); + stmt.execute(sql2); + + String sqlin2 = "insert into ctstable1 values (1,'COFFEE-Desc')"; + stmt.execute(sqlin2); + sqlin2 = "insert into ctstable1 values (2,'COFFEE-Desc2')"; + stmt.execute(sqlin2); + sqlin2 = "insert into ctstable1 values (3,'COFFEE-Desc3')"; + stmt.execute(sqlin2); + + String sqlin1 = "insert into ctstable2 values (9,'COFFEE-9',9.0, 1)"; + stmt.execute(sqlin1); + sqlin1 = "insert into ctstable2 values (10,'COFFEE-10',10.0, 2)"; + stmt.execute(sqlin1); + sqlin1 = "insert into ctstable2 values (11,'COFFEE-11',11.0, 3)"; + stmt.execute(sqlin1); + } } private void testAddBatch1Internal(String mode) { @@ -167,40 +164,41 @@ private void testAddBatch1Internal(String mode) { modifyConnectionForBulkCopyAPI((SQLServerConnection) connection); } - pstmt = connection.prepareStatement(sPrepStmt); - pstmt.setInt(1, 2); - pstmt.addBatch(); + try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { + pstmt.setInt(1, 2); + pstmt.addBatch(); - pstmt.setInt(1, 3); - pstmt.addBatch(); + pstmt.setInt(1, 3); + pstmt.addBatch(); - pstmt.setInt(1, 4); - pstmt.addBatch(); + pstmt.setInt(1, 4); + pstmt.addBatch(); - int[] updateCount = pstmt.executeBatch(); - int updateCountlen = updateCount.length; + int[] updateCount = pstmt.executeBatch(); + int updateCountlen = updateCount.length; - assertTrue(updateCountlen == 3, TestResource.getResource("R_addBatchFailed") + ": " - + TestResource.getResource("R_incorrectUpdateCount")); + assertTrue(updateCountlen == 3, TestResource.getResource("R_addBatchFailed") + ": " + + TestResource.getResource("R_incorrectUpdateCount")); - String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; + String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; - pstmt1 = connection.prepareStatement(sPrepStmt1); + try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1)) { - // 2 is the number that is set First for Type Id in Prepared Statement - for (int n = 2; n <= 4; n++) { - pstmt1.setInt(1, n); - rs = pstmt1.executeQuery(); - rs.next(); - retValue[i++] = rs.getInt(1); - } - - pstmt1.close(); + // 2 is the number that is set First for Type Id in Prepared Statement + for (int n = 2; n <= 4; n++) { + pstmt1.setInt(1, n); + try (ResultSet rs = pstmt1.executeQuery()) { + rs.next(); + retValue[i++] = rs.getInt(1); + } + } + } - for (int j = 0; j < updateCount.length; j++) { + for (int j = 0; j < updateCount.length; j++) { - if (updateCount[j] != retValue[j] && updateCount[j] != Statement.SUCCESS_NO_INFO) { - fail(TestResource.getResource("R_incorrectUpdateCount")); + if (updateCount[j] != retValue[j] && updateCount[j] != Statement.SUCCESS_NO_INFO) { + fail(TestResource.getResource("R_incorrectUpdateCount")); + } } } } catch (Exception e) { @@ -218,38 +216,25 @@ private void modifyConnectionForBulkCopyAPI(SQLServerConnection con) throws Exce @BeforeAll public static void testSetup() throws TestAbortedException, Exception { - assumeTrue(13 <= new DBConnection(connectionString).getServerVersion(), - TestResource.getResource("R_Incompat_SQLServerVersion")); - connection = DriverManager.getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); - stmt = (SQLServerStatement) connection.createStatement(); + try (DBConnection con = new DBConnection(connectionString)) { + assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); + } + dropTable(); createTable(); } private static void dropTable() throws SQLException { - Utils.dropTableIfExists("ctstable2", stmt); - Utils.dropTableIfExists("ctstable1", stmt); + try (Connection connection = DriverManager + .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); + Statement stmt = (SQLServerStatement) connection.createStatement()) { + Utils.dropTableIfExists("ctstable2", stmt); + Utils.dropTableIfExists("ctstable1", stmt); + } } @AfterAll public static void terminateVariation() throws SQLException { - dropTable(); - - if (null != connection) { - connection.close(); - } - if (null != pstmt) { - pstmt.close(); - } - if (null != pstmt1) { - pstmt1.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java index 2223f612d..69b8cf2ea 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java @@ -33,8 +33,6 @@ @RunWith(JUnitPlatform.class) public class BatchTriggerTest extends AbstractTest { - static Statement stmt = null; - static Connection connection = null; static String tableName = "triggerTable"; static String triggerName = "triggerTest"; static String insertQuery = "insert into " + tableName @@ -47,21 +45,13 @@ public class BatchTriggerTest extends AbstractTest { */ @Test public void statementTest() throws SQLException { - Statement stmt = null; - try { - stmt = connection.createStatement(); + try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { stmt.addBatch(insertQuery); stmt.executeBatch(); fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { assertTrue(e.getMessage().equalsIgnoreCase(TestResource.getResource("R_customErrorMessage"))); } - - finally { - if (stmt != null) { - stmt.close(); - } - } } /** @@ -71,19 +61,14 @@ public void statementTest() throws SQLException { */ @Test public void preparedStatementTest() throws SQLException { - PreparedStatement pstmt = null; - try { - pstmt = connection.prepareStatement(insertQuery); + try (Connection connection = DriverManager.getConnection(connectionString); PreparedStatement pstmt = connection.prepareStatement(insertQuery)) { + pstmt.addBatch(); pstmt.executeBatch(); fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { assertTrue(e.getMessage().equalsIgnoreCase(TestResource.getResource("R_customErrorMessage"))); - } finally { - if (pstmt != null) { - pstmt.close(); - } } } @@ -94,10 +79,13 @@ public void preparedStatementTest() throws SQLException { * @throws SQLException */ private static void createTrigger(String triggerName) throws SQLException { - String sql = "create trigger " + triggerName + " on " + tableName + " for insert " + "as " + "begin " - + "if (select col1 from " + tableName + ") > 10 " + "begin " + "return " + "end " + "RAISERROR ('" - + TestResource.getResource("R_customErrorMessage") + "', 16, 0) " + "rollback transaction " + "end"; - stmt.execute(sql); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + String sql = "create trigger " + triggerName + " on " + tableName + " for insert " + "as " + "begin " + + "if (select col1 from " + tableName + ") > 10 " + "begin " + "return " + "end " + "RAISERROR ('" + + TestResource.getResource("R_customErrorMessage") + "', 16, 0) " + "rollback transaction " + "end"; + stmt.execute(sql); + } } /** @@ -106,8 +94,11 @@ private static void createTrigger(String triggerName) throws SQLException { * @throws SQLException */ private static void createTable() throws SQLException { - String sql = "create table " + tableName + " ( col1 int, col2 varchar(50), col3 varchar(10), col4 int)"; - stmt.execute(sql); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + String sql = "create table " + tableName + " ( col1 int, col2 varchar(50), col3 varchar(10), col4 int)"; + stmt.execute(sql); + } } /** @@ -118,14 +109,15 @@ private static void createTable() throws SQLException { */ @BeforeAll public static void testSetup() throws TestAbortedException, Exception { - connection = DriverManager.getConnection(connectionString); - stmt = (SQLServerStatement) connection.createStatement(); - stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" - + " WHERE [type] = 'TR' AND [name] = '" + triggerName + "'\r\n" + " )\r\n" + " DROP TRIGGER " - + triggerName + ";"); - dropTable(); - createTable(); - createTrigger(triggerName); + try (Connection connection = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { + stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" + + " WHERE [type] = 'TR' AND [name] = '" + triggerName + "'\r\n" + " )\r\n" + + " DROP TRIGGER " + triggerName + ";"); + dropTable(); + createTable(); + createTrigger(triggerName); + } } /** @@ -134,7 +126,9 @@ public static void testSetup() throws TestAbortedException, Exception { * @throws SQLException */ private static void dropTable() throws SQLException { - Utils.dropTableIfExists(tableName, stmt); + try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { + Utils.dropTableIfExists(tableName, stmt); + } } /** @@ -144,17 +138,13 @@ private static void dropTable() throws SQLException { */ @AfterAll public static void terminateVariation() throws SQLException { - dropTable(); - stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" - + " WHERE [type] = 'TR' AND [name] = '" + triggerName + "'\r\n" + " )\r\n" + " DROP TRIGGER " - + triggerName + ";"); + try (Connection connection = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { - if (null != connection) { - connection.close(); + dropTable(); + stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" + + " WHERE [type] = 'TR' AND [name] = '" + triggerName + "'\r\n" + " )\r\n" + + " DROP TRIGGER " + triggerName + ";"); } - if (null != stmt) { - stmt.close(); - } - } } 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 27269cf89..33bda0a9b 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 @@ -31,7 +31,6 @@ */ @RunWith(JUnitPlatform.class) public class CallableMixedTest extends AbstractTest { - Connection connection = null; String tableN = RandomUtil.getIdentifier("TFOO3"); String procN = RandomUtil.getIdentifier("SPFOO3"); String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); @@ -66,28 +65,35 @@ public void datatypesTest() throws SQLException { callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); // get results and a value - ResultSet rs = callableStatement.executeQuery(); - rs.next(); - - assertEquals(rs.getInt(1), 0, TestResource.getResource("R_setDataNotEqual")); - assertEquals(callableStatement.getInt((int) 5), -5372, TestResource.getResource("R_setDataNotEqual")); - - // do nothing and reexecute - rs = callableStatement.executeQuery(); + try (ResultSet rs = callableStatement.executeQuery()) { + rs.next(); + + assertEquals(rs.getInt(1), 0, TestResource.getResource("R_setDataNotEqual")); + assertEquals(callableStatement.getInt((int) 5), -5372, + TestResource.getResource("R_setDataNotEqual")); + } + + // do nothing and re-execute + try (ResultSet rs = callableStatement.executeQuery()) { + } + // get the param without getting the resultset - rs = callableStatement.executeQuery(); + try (ResultSet rs = callableStatement.executeQuery()) { assertEquals(callableStatement.getInt((int) 1), -2147483648, TestResource.getResource("R_setDataNotEqual")); - - rs = callableStatement.executeQuery(); + } + + try (ResultSet rs = callableStatement.executeQuery()) { rs.next(); assertEquals(rs.getInt(1), 0, TestResource.getResource("R_setDataNotEqual")); assertEquals(callableStatement.getInt((int) 1), -2147483648, TestResource.getResource("R_setDataNotEqual")); assertEquals(callableStatement.getInt((int) 5), -5372, TestResource.getResource("R_setDataNotEqual")); - rs = callableStatement.executeQuery(); - rs.close(); + } + + try (ResultSet rs = callableStatement.executeQuery()) { + } } terminateVariation(statement); } 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 6966889dd..cf28d2402 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 @@ -31,7 +31,6 @@ @RunWith(JUnitPlatform.class) public class NamedParamMultiPartTest extends AbstractTest { private static final String dataPut = "eminem"; - private static Connection connection = null; String procedureName = "mystoredproc"; /** @@ -41,8 +40,8 @@ public class NamedParamMultiPartTest extends AbstractTest { */ @BeforeAll public static void beforeAll() throws SQLException { - connection = DriverManager.getConnection(connectionString); - try (Statement statement = connection.createStatement()) { + try (Connection 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 + "'"); @@ -56,7 +55,8 @@ public static void beforeAll() throws SQLException { */ @Test public void update1() throws Exception { - try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); + CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); String data = cs.getString("p_out"); @@ -71,7 +71,8 @@ public void update1() throws Exception { */ @Test public void update2() throws Exception { - try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); + CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -88,7 +89,8 @@ public void update2() throws Exception { public void update3() throws Exception { String catalog = connection.getCatalog(); String storedproc = "[" + catalog + "]" + ".[dbo].[mystoredproc]"; - try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); + CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -103,7 +105,8 @@ public void update3() throws Exception { */ @Test public void update4() throws Exception { - try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); + CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -118,7 +121,8 @@ public void update4() throws Exception { */ @Test public void update5() throws Exception { - try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); + CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -134,7 +138,8 @@ public void update5() throws Exception { public void update6() throws Exception { String catalog = connection.getCatalog(); String storedproc = catalog + ".dbo." + procedureName; - try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); + CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -149,13 +154,9 @@ public void update6() throws Exception { */ @AfterAll public static void afterAll() throws SQLException { - try (Statement stmt = connection.createStatement()) { + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { Utils.dropProcedureIfExists("mystoredproc", stmt); - } finally { - if (connection != null) { - connection.close(); - } } } - } 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 7f0c8ad47..5f2b89fe2 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 @@ -43,15 +43,15 @@ private void executeSQL(SQLServerConnection conn, String sql) throws SQLExceptio } private int executeSQLReturnFirstInt(SQLServerConnection conn, String sql) throws SQLException { - Statement stmt = conn.createStatement(); - ResultSet result = stmt.executeQuery(sql); + try (Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery(sql)) { - int returnValue = -1; + int returnValue = -1; - if (result.next()) - returnValue = result.getInt(1); + if (result.next()) + returnValue = result.getInt(1); - return returnValue; + return returnValue; + } } /** @@ -125,9 +125,13 @@ public void testBatchedUnprepare() throws SQLException { * executeSQLReturnFirstInt(con, verifyTotalCacheUsesQuery)); assertTrue(expectedCacheHits - * allowedDiscrepency < executeSQLReturnFirstInt(con, verifyTotalCacheUsesQuery)); */ + } finally { + // Verify clean-up happened on connection close. + assertSame(0, conOuter.getDiscardedServerPreparedStatementCount()); + if (null != conOuter) { + conOuter.close(); + } } - // Verify clean-up happened on connection close. - assertSame(0, conOuter.getDiscardedServerPreparedStatementCount()); } /** @@ -326,114 +330,126 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws dataSource.setServerPreparedStatementDiscardThreshold( dataSource.getServerPreparedStatementDiscardThreshold() + 1); // Verify connection from data source has same parameters. - SQLServerConnection connDataSource = (SQLServerConnection) dataSource.getConnection(); - assertSame(dataSource.getStatementPoolingCacheSize(), connDataSource.getStatementPoolingCacheSize()); - assertSame(dataSource.getEnablePrepareOnFirstPreparedStatementCall(), - connDataSource.getEnablePrepareOnFirstPreparedStatementCall()); - assertSame(dataSource.getServerPreparedStatementDiscardThreshold(), - connDataSource.getServerPreparedStatementDiscardThreshold()); - + try (SQLServerConnection connDataSource = (SQLServerConnection) dataSource.getConnection()) { + assertSame(dataSource.getStatementPoolingCacheSize(), connDataSource.getStatementPoolingCacheSize()); + assertSame(dataSource.getEnablePrepareOnFirstPreparedStatementCall(), + connDataSource.getEnablePrepareOnFirstPreparedStatementCall()); + assertSame(dataSource.getServerPreparedStatementDiscardThreshold(), + connDataSource.getServerPreparedStatementDiscardThreshold()); + } // Test connection string properties. // Test disableStatementPooling String connectionStringDisableStatementPooling = connectionString + ";disableStatementPooling=true;"; - SQLServerConnection connectionDisableStatementPooling = (SQLServerConnection) DriverManager - .getConnection(connectionStringDisableStatementPooling); - connectionDisableStatementPooling.setStatementPoolingCacheSize(10); // to turn on caching and check if - // disableStatementPooling is true, even - // setting cachesize won't matter and will - // disable it. - assertSame(10, connectionDisableStatementPooling.getStatementPoolingCacheSize()); - assertTrue(!connectionDisableStatementPooling.isStatementPoolingEnabled()); - String connectionStringEnableStatementPooling = connectionString + ";disableStatementPooling=false;"; - SQLServerConnection connectionEnableStatementPooling = (SQLServerConnection) DriverManager - .getConnection(connectionStringEnableStatementPooling); - connectionEnableStatementPooling.setStatementPoolingCacheSize(10); // to turn on caching. - assertTrue(0 < connectionEnableStatementPooling.getStatementPoolingCacheSize()); // for now, it won't affect if - // disable is false or true. - // Since - // statementPoolingCacheSize is - // set to 0 as default. - // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, thus - // disabling the prepared statement metadata caching. - assertTrue(connectionEnableStatementPooling.isStatementPoolingEnabled()); - + try (SQLServerConnection connectionDisableStatementPooling = (SQLServerConnection) DriverManager + .getConnection(connectionStringDisableStatementPooling)) { + // to turn on caching and check if disableStatementPooling is true, even setting cachesize won't matter and + // will disable it. + connectionDisableStatementPooling.setStatementPoolingCacheSize(10); + assertSame(10, connectionDisableStatementPooling.getStatementPoolingCacheSize()); + assertTrue(!connectionDisableStatementPooling.isStatementPoolingEnabled()); + String connectionStringEnableStatementPooling = connectionString + ";disableStatementPooling=false;"; + SQLServerConnection connectionEnableStatementPooling = (SQLServerConnection) DriverManager + .getConnection(connectionStringEnableStatementPooling); + connectionEnableStatementPooling.setStatementPoolingCacheSize(10); // to turn on caching. + + // for now, it won't affect if disable is false or true. Since statementPoolingCacheSize is set to 0 as + // default. + assertTrue(0 < connectionEnableStatementPooling.getStatementPoolingCacheSize()); + // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, + // thus + // disabling the prepared statement metadata caching. + assertTrue(connectionEnableStatementPooling.isStatementPoolingEnabled()); + } + String connectionPropertyStringEnableStatementPooling = connectionString + ";disableStatementPooling=false;statementPoolingCacheSize=10"; - SQLServerConnection connectionPropertyEnableStatementPooling = (SQLServerConnection) DriverManager - .getConnection(connectionPropertyStringEnableStatementPooling); - assertTrue(0 < connectionPropertyEnableStatementPooling.getStatementPoolingCacheSize()); // for now, it won't - // affect if disable is - // false or true. Since - // statementPoolingCacheSize - // is set to 0 as - // default. - // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, thus - // disabling the prepared statement metadata caching. - assertTrue(connectionPropertyEnableStatementPooling.isStatementPoolingEnabled()); - + try (SQLServerConnection connectionPropertyEnableStatementPooling = (SQLServerConnection) DriverManager + .getConnection(connectionPropertyStringEnableStatementPooling)) { + // for now, it won't affect if disable is false or true. Since statementPoolingCacheSize is set to 0 as + // default. + assertTrue(0 < connectionPropertyEnableStatementPooling.getStatementPoolingCacheSize()); + // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, + // thus + // disabling the prepared statement metadata caching. + assertTrue(connectionPropertyEnableStatementPooling.isStatementPoolingEnabled()); + } + String connectionPropertyStringDisableStatementPooling = connectionString + ";disableStatementPooling=true;statementPoolingCacheSize=10"; - SQLServerConnection connectionPropertyDisableStatementPooling = (SQLServerConnection) DriverManager - .getConnection(connectionPropertyStringDisableStatementPooling); - assertTrue(0 < connectionPropertyDisableStatementPooling.getStatementPoolingCacheSize()); // for now, it won't - // affect if disable - // is false or true. - // Since - // statementPoolingCacheSize - // is set to 0 as - // default. - // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, thus - // disabling the prepared statement metadata caching. - assertTrue(!connectionPropertyDisableStatementPooling.isStatementPoolingEnabled()); - + try (SQLServerConnection connectionPropertyDisableStatementPooling = (SQLServerConnection) DriverManager + .getConnection(connectionPropertyStringDisableStatementPooling)) { + assertTrue(0 < connectionPropertyDisableStatementPooling.getStatementPoolingCacheSize()); // for now, it + // won't + // affect if + // disable + // is false or + // true. + // Since + // statementPoolingCacheSize + // is set to 0 as + // default. + // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, + // thus + // disabling the prepared statement metadata caching. + assertTrue(!connectionPropertyDisableStatementPooling.isStatementPoolingEnabled()); + } + String connectionPropertyStringDisableStatementPooling2 = connectionString + ";disableStatementPooling=false;statementPoolingCacheSize=0"; - SQLServerConnection connectionPropertyDisableStatementPooling2 = (SQLServerConnection) DriverManager - .getConnection(connectionPropertyStringDisableStatementPooling2); - assertTrue(0 == connectionPropertyDisableStatementPooling2.getStatementPoolingCacheSize()); // for now, it won't - // affect if disable - // is false or true. - // Since - // statementPoolingCacheSize - // is set to 0 as - // default. - // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, thus - // disabling the prepared statement metadata caching. - assertTrue(!connectionPropertyDisableStatementPooling2.isStatementPoolingEnabled()); - + try (SQLServerConnection connectionPropertyDisableStatementPooling2 = (SQLServerConnection) DriverManager + .getConnection(connectionPropertyStringDisableStatementPooling2)) { + assertTrue(0 == connectionPropertyDisableStatementPooling2.getStatementPoolingCacheSize()); // for now, it + // won't + // affect if + // disable + // is false or + // true. + // Since + // statementPoolingCacheSize + // is set to 0 + // as + // default. + // If only disableStatementPooling is set to true, it makes sure that statementPoolingCacheSize is zero, + // thus + // disabling the prepared statement metadata caching. + assertTrue(!connectionPropertyDisableStatementPooling2.isStatementPoolingEnabled()); + } + // Test EnablePrepareOnFirstPreparedStatementCall String connectionStringNoExecuteSQL = connectionString + ";enablePrepareOnFirstPreparedStatementCall=true;"; - SQLServerConnection connectionNoExecuteSQL = (SQLServerConnection) DriverManager - .getConnection(connectionStringNoExecuteSQL); - assertSame(true, connectionNoExecuteSQL.getEnablePrepareOnFirstPreparedStatementCall()); - + try (SQLServerConnection connectionNoExecuteSQL = (SQLServerConnection) DriverManager + .getConnection(connectionStringNoExecuteSQL)) { + assertSame(true, connectionNoExecuteSQL.getEnablePrepareOnFirstPreparedStatementCall()); + } + // Test ServerPreparedStatementDiscardThreshold String connectionStringThreshold3 = connectionString + ";ServerPreparedStatementDiscardThreshold=3;"; - SQLServerConnection connectionThreshold3 = (SQLServerConnection) DriverManager - .getConnection(connectionStringThreshold3); - assertSame(3, connectionThreshold3.getServerPreparedStatementDiscardThreshold()); + try (SQLServerConnection connectionThreshold3 = (SQLServerConnection) DriverManager + .getConnection(connectionStringThreshold3)) { + assertSame(3, connectionThreshold3.getServerPreparedStatementDiscardThreshold()); + } // Test combination of EnablePrepareOnFirstPreparedStatementCall and ServerPreparedStatementDiscardThreshold String connectionStringThresholdAndNoExecuteSQL = connectionString + ";ServerPreparedStatementDiscardThreshold=3;enablePrepareOnFirstPreparedStatementCall=true;"; - SQLServerConnection connectionThresholdAndNoExecuteSQL = (SQLServerConnection) DriverManager - .getConnection(connectionStringThresholdAndNoExecuteSQL); - assertSame(true, connectionThresholdAndNoExecuteSQL.getEnablePrepareOnFirstPreparedStatementCall()); - assertSame(3, connectionThresholdAndNoExecuteSQL.getServerPreparedStatementDiscardThreshold()); - + try (SQLServerConnection connectionThresholdAndNoExecuteSQL = (SQLServerConnection) DriverManager + .getConnection(connectionStringThresholdAndNoExecuteSQL)) { + assertSame(true, connectionThresholdAndNoExecuteSQL.getEnablePrepareOnFirstPreparedStatementCall()); + assertSame(3, connectionThresholdAndNoExecuteSQL.getServerPreparedStatementDiscardThreshold()); + } + // Test that an error is thrown for invalid connection string property values (non int/bool). - try { - String connectionStringThresholdError = connectionString + ";ServerPreparedStatementDiscardThreshold=hej;"; - DriverManager.getConnection(connectionStringThresholdError); + String connectionStringThresholdError = connectionString + ";ServerPreparedStatementDiscardThreshold=hej;"; + try (SQLServerConnection con = (SQLServerConnection)DriverManager.getConnection(connectionStringThresholdError)) { fail("Error for invalid ServerPreparedStatementDiscardThresholdexpected."); } catch (SQLException e) { // Good! } - try { - String connectionStringNoExecuteSQLError = connectionString - + ";enablePrepareOnFirstPreparedStatementCall=dobidoo;"; - DriverManager.getConnection(connectionStringNoExecuteSQLError); + + String connectionStringNoExecuteSQLError = connectionString + + ";enablePrepareOnFirstPreparedStatementCall=dobidoo;"; + try (SQLServerConnection con = (SQLServerConnection)DriverManager.getConnection(connectionStringNoExecuteSQLError)) { fail("Error for invalid enablePrepareOnFirstPreparedStatementCall expected."); } catch (SQLException e) { // Good! @@ -648,6 +664,10 @@ private void testStatementPoolingInternal(String mode) throws Exception { fail(TestResource.getResource("R_invalidGetPreparedStatementHandle")); } catch (Exception e) { // Good! + } finally { + if (null != outer) { + outer.close(); + } } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java index 1cdac5dc2..ba9c39e0a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java @@ -41,59 +41,55 @@ public class RegressionTest extends AbstractTest { */ @Test public void testServerCursorPStmt() throws SQLException { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - - PreparedStatement pstmt = null; - ResultSet rs = null; - - // expected values - int numRowsInResult = 1; - String col3Value = "India"; - String col3Lookup = "IN"; - - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (1, 'CAN', 'Canada')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (2, 'USA', 'United States of America')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (3, 'JPN', 'Japan')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (4, '" + col3Lookup + "', '" + col3Value + "')"); - - // create stored proc - String storedProcString; - - if (DBConnection.isSqlAzure(con)) { - // On SQL Azure, 'SELECT INTO' is not supported. So do not use it. - storedProcString = "CREATE PROCEDURE " + procName + " @param varchar(3) AS SELECT col3 FROM " + tableName - + " WHERE col2 = @param"; - } else { - // On SQL Server - storedProcString = "CREATE PROCEDURE " + procName + " @param varchar(3) AS SELECT col3 INTO #TMPTABLE FROM " - + tableName + " WHERE col2 = @param SELECT col3 FROM #TMPTABLE"; - } + // expected values + int numRowsInResult = 1; + String col3Value = "India"; + String col3Lookup = "IN"; - stmt.executeUpdate(storedProcString); - - // execute stored proc via pstmt - pstmt = con.prepareStatement("EXEC " + procName + " ?", ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - pstmt.setString(1, col3Lookup); - - // should return 1 row - rs = pstmt.executeQuery(); - rs.last(); - assertEquals(rs.getRow(), numRowsInResult, - TestResource.getResource("R_valueNotMatch") + rs.getRow() + ", " + numRowsInResult); - rs.beforeFirst(); - while (rs.next()) { - assertEquals(rs.getString(1), col3Value, - TestResource.getResource("R_valueNotMatch") + rs.getString(1) + ", " + col3Value); - } + stmt.executeUpdate( + "CREATE TABLE " + tableName + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); + stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (1, 'CAN', 'Canada')"); + stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (2, 'USA', 'United States of America')"); + stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (3, 'JPN', 'Japan')"); + stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (4, '" + col3Lookup + "', '" + col3Value + "')"); + + // create stored proc + String storedProcString; + + if (DBConnection.isSqlAzure(con)) { + // On SQL Azure, 'SELECT INTO' is not supported. So do not use it. + storedProcString = "CREATE PROCEDURE " + procName + " @param varchar(3) AS SELECT col3 FROM " + + tableName + " WHERE col2 = @param"; + } else { + // On SQL Server + storedProcString = "CREATE PROCEDURE " + procName + + " @param varchar(3) AS SELECT col3 INTO #TMPTABLE FROM " + tableName + + " WHERE col2 = @param SELECT col3 FROM #TMPTABLE"; + } - if (null != stmt) - stmt.close(); - if (null != con) - con.close(); + stmt.executeUpdate(storedProcString); + + // execute stored proc via pstmt + try (PreparedStatement pstmt = con.prepareStatement("EXEC " + procName + " ?", + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { + pstmt.setString(1, col3Lookup); + + // should return 1 row + try (ResultSet rs = pstmt.executeQuery()) { + rs.last(); + assertEquals(rs.getRow(), numRowsInResult, + TestResource.getResource("R_valueNotMatch") + rs.getRow() + ", " + numRowsInResult); + rs.beforeFirst(); + while (rs.next()) { + assertEquals(rs.getString(1), col3Value, + TestResource.getResource("R_valueNotMatch") + rs.getString(1) + ", " + col3Value); + } + } + } + } } /** @@ -103,33 +99,31 @@ public void testServerCursorPStmt() throws SQLException { */ @Test public void testSelectIntoUpdateCount() throws SQLException { - SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - - // Azure does not do SELECT INTO - if (!DBConnection.isSqlAzure(con)) { - final String tableName = "[#SourceTableForSelectInto]"; - - Statement stmt = con.createStatement(); - stmt.executeUpdate( - "CREATE TABLE " + tableName + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (1, 'CAN', 'Canada')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (2, 'USA', 'United States of America')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (3, 'JPN', 'Japan')"); - - // expected values - int numRowsToCopy = 2; - - PreparedStatement ps = con - .prepareStatement("SELECT * INTO #TMPTABLE FROM " + tableName + " WHERE col1 <= ?"); - ps.setInt(1, numRowsToCopy); - int updateCount = ps.executeUpdate(); - assertEquals(numRowsToCopy, updateCount, TestResource.getResource("R_incorrectUpdateCount")); - - if (null != stmt) - stmt.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + + // Azure does not do SELECT INTO + if (!DBConnection.isSqlAzure(con)) { + final String tableName = "[#SourceTableForSelectInto]"; + + try (Statement stmt = con.createStatement()) { + stmt.executeUpdate("CREATE TABLE " + tableName + + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); + stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (1, 'CAN', 'Canada')"); + stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (2, 'USA', 'United States of America')"); + stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (3, 'JPN', 'Japan')"); + + // expected values + int numRowsToCopy = 2; + + try (PreparedStatement ps = con + .prepareStatement("SELECT * INTO #TMPTABLE FROM " + tableName + " WHERE col1 <= ?")) { + ps.setInt(1, numRowsToCopy); + int updateCount = ps.executeUpdate(); + assertEquals(numRowsToCopy, updateCount, TestResource.getResource("R_incorrectUpdateCount")); + } + } + } } - if (null != con) - con.close(); } /** @@ -142,54 +136,52 @@ public void testUpdateQuery() throws SQLException { assumeTrue("JDBC41".equals(Utils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - String sql; - SQLServerPreparedStatement pstmt = null; - JDBCType[] targets = {JDBCType.INTEGER, JDBCType.SMALLINT}; - int rows = 3; - final String tableName = "[updateQuery]"; - - Statement stmt = con.createStatement(); - Utils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("CREATE TABLE " + tableName + " (" + "c1 int null," + "PK int NOT NULL PRIMARY KEY" + ")"); - - /* - * populate table - */ - sql = "insert into " + tableName + " values(" + "?,?" + ")"; - pstmt = (SQLServerPreparedStatement) con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY, connection.getHoldability()); - - for (int i = 1; i <= rows; i++) { - pstmt.setObject(1, i, JDBCType.INTEGER); - pstmt.setObject(2, i, JDBCType.INTEGER); - pstmt.executeUpdate(); - } + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String sql; + JDBCType[] targets = {JDBCType.INTEGER, JDBCType.SMALLINT}; + int rows = 3; + final String tableName = "[updateQuery]"; - /* - * Update table - */ - sql = "update " + tableName + " SET c1= ? where PK =1"; - for (int i = 1; i <= rows; i++) { - pstmt = (SQLServerPreparedStatement) con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY); - for (JDBCType target : targets) { - pstmt.setObject(1, 5 + i, target); - pstmt.executeUpdate(); + Utils.dropTableIfExists(tableName, stmt); + stmt.executeUpdate( + "CREATE TABLE " + tableName + " (" + "c1 int null," + "PK int NOT NULL PRIMARY KEY" + ")"); + + /* + * populate table + */ + sql = "insert into " + tableName + " values(" + "?,?" + ")"; + try (PreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(sql, + ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, con.getHoldability())) { + + for (int i = 1; i <= rows; i++) { + pstmt.setObject(1, i, JDBCType.INTEGER); + pstmt.setObject(2, i, JDBCType.INTEGER); + pstmt.executeUpdate(); + } + } + /* + * Update table + */ + sql = "update " + tableName + " SET c1= ? where PK =1"; + for (int i = 1; i <= rows; i++) { + try (PreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(sql, + ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { + for (JDBCType target : targets) { + pstmt.setObject(1, 5 + i, target); + pstmt.executeUpdate(); + } + } } - } - /* - * Verify - */ - ResultSet rs = stmt.executeQuery("select * from " + tableName); - rs.next(); - assertEquals(rs.getInt(1), 8, "Value mismatch"); - - if (null != stmt) - stmt.close(); - if (null != con) - con.close(); + /* + * Verify + */ + try (ResultSet rs = stmt.executeQuery("select * from " + tableName)) { + rs.next(); + assertEquals(rs.getInt(1), 8, "Value mismatch"); + } + } } private String xmlTableName = "try_SQLXML_Table"; @@ -204,29 +196,30 @@ public void testXmlQuery() throws SQLException { assumeTrue("JDBC41".equals(Utils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - Connection connection = DriverManager.getConnection(connectionString); - - Statement stmt = connection.createStatement(); - - dropTables(stmt); - createTable(stmt); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + dropTables(stmt); + createTable(stmt); - String sql = "UPDATE " + xmlTableName + " SET [c2] = ?, [c3] = ?"; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql); + String sql = "UPDATE " + xmlTableName + " SET [c2] = ?, [c3] = ?"; + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { - pstmt.setObject(1, null); - pstmt.setObject(2, null, Types.SQLXML); - pstmt.executeUpdate(); - - pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql); - pstmt.setObject(1, null, Types.SQLXML); - pstmt.setObject(2, null); - pstmt.executeUpdate(); + pstmt.setObject(1, null); + pstmt.setObject(2, null, Types.SQLXML); + pstmt.executeUpdate(); + } + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { + pstmt.setObject(1, null, Types.SQLXML); + pstmt.setObject(2, null); + pstmt.executeUpdate(); + } - pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql); - pstmt.setObject(1, null); - pstmt.setObject(2, null, Types.SQLXML); - pstmt.executeUpdate(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { + pstmt.setObject(1, null); + pstmt.setObject(2, null, Types.SQLXML); + pstmt.executeUpdate(); + } + } } private void dropTables(Statement stmt) throws SQLException { @@ -242,10 +235,10 @@ private void createTable(Statement stmt) throws SQLException { @AfterAll public static void terminate() throws SQLException { - SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - Utils.dropTableIfExists(tableName, stmt); - Utils.dropProcedureIfExists(procName, stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropProcedureIfExists(procName, stmt); + } } - } 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 8eff3089b..fc9bde06b 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 @@ -75,31 +75,30 @@ public class TCAttentionHandling { @BeforeEach public void init() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - con.setAutoCommit(false); - Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } catch (SQLException e) {} - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT PRIMARY KEY, col2 VARCHAR(" - + TEST_STRING.length() + "))"); - for (int i = 0; i < NUM_TABLE_ROWS; i++) - stmt.executeUpdate( - "INSERT INTO " + tableName + " (col1, col2) VALUES (" + i + ", '" + TEST_STRING + "')"); - stmt.close(); - con.commit(); - con.close(); + try (Connection con = DriverManager.getConnection(connectionString)) { + con.setAutoCommit(false); + try (Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } catch (SQLException e) {} + stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT PRIMARY KEY, col2 VARCHAR(" + + TEST_STRING.length() + "))"); + for (int i = 0; i < NUM_TABLE_ROWS; i++) + stmt.executeUpdate( + "INSERT INTO " + tableName + " (col1, col2) VALUES (" + i + ", '" + TEST_STRING + "')"); + } + con.commit(); + } } @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(); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } catch (SQLException e) {} + } } /** @@ -110,18 +109,17 @@ public void terminate() throws Exception { @Test public void testCancelBeforeExecute() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - stmt.cancel(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); - int numSelectedRows = 0; - while (rs.next()) - ++numSelectedRows; + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + stmt.cancel(); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); + int numSelectedRows = 0; + while (rs.next()) + ++numSelectedRows; - // Wrong number of rows returned - assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); - stmt.close(); - con.close(); + // Wrong number of rows returned + assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); + } } /** @@ -135,30 +133,27 @@ public void testCancelBeforeExecute() throws Exception { */ @Test public void testErrorInRequest() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - - PreparedStatement ps = con.prepareStatement("UPDATE " + tableName + " SET col2 = ? WHERE col1 = ?"); - ps.setString(1, TEST_STRING); - for (int i = 0; i < MIN_TABLE_ROWS; i++) { - ps.setInt(2, i); + try (Connection con = DriverManager.getConnection(connectionString); PreparedStatement ps = con + .prepareStatement("UPDATE " + tableName + " SET col2 = ? WHERE col1 = ?")) { + ps.setString(1, TEST_STRING); + for (int i = 0; i < MIN_TABLE_ROWS; i++) { + ps.setInt(2, i); + ps.addBatch(); + } + ps.setCharacterStream(1, new StringReader(TEST_STRING), TEST_STRING.length() - 1); ps.addBatch(); - } - ps.setCharacterStream(1, new StringReader(TEST_STRING), TEST_STRING.length() - 1); - ps.addBatch(); - try { - ps.executeBatch(); - } catch (SQLException e) { - assertEquals( - "The stream value is not the specified length. The specified length was " - + (TEST_STRING.length() - 1) + ", the actual length is " + TEST_STRING.length() + ".", - e.getMessage(), TestResource.getResource("R_unexpectedException")); - } + try { + ps.executeBatch(); + } catch (SQLException e) { + assertEquals("The stream value is not the specified length. The specified length was " + + (TEST_STRING.length() - 1) + ", the actual length is " + TEST_STRING.length() + ".", + e.getMessage(), TestResource.getResource("R_unexpectedException")); + } - // Successfully closing the PreparedStatement is verification enough that the connection is - // still usable and that there isn't a left over attention ack on the wire. - ps.close(); - con.close(); + // Successfully closing the PreparedStatement is verification enough that the connection is + // still usable and that there isn't a left over attention ack on the wire. + } } /** @@ -172,44 +167,42 @@ public void testErrorInRequest() throws Exception { public void testQueryTimeout() throws Exception { long elapsedMillis; - Connection con = DriverManager.getConnection(connectionString); - PreparedStatement ps = con.prepareStatement("WAITFOR DELAY '00:00:07'"); + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement ps = con.prepareStatement("WAITFOR DELAY '00:00:07'")) { - // First execution: - // Verify timeout actually cancels statement execution. - elapsedMillis = -System.currentTimeMillis(); - ps.setQueryTimeout(2); - try { - ps.execute(); + // First execution: + // Verify timeout actually cancels statement execution. + elapsedMillis = -System.currentTimeMillis(); + ps.setQueryTimeout(2); + try { + ps.execute(); - assertEquals(false, true, TestResource.getResource("R_executionNotTimeout")); - } catch (SQLException e) { - assertTrue(TestResource.getResource("R_queryTimedOut").equalsIgnoreCase(e.getMessage()), - TestResource.getResource("R_unexpectedException")); - assertTrue("The query has timed out.".equalsIgnoreCase(e.getMessage()), - TestResource.getResource("R_unexpectedException")); - } - elapsedMillis += System.currentTimeMillis(); - if (elapsedMillis >= 3000) { - assertEquals(2000, (int) elapsedMillis, TestResource.getResource("R_executionTooLong")); - } + assertEquals(false, true, TestResource.getResource("R_executionNotTimeout")); + } catch (SQLException e) { + assertTrue(TestResource.getResource("R_queryTimedOut").equalsIgnoreCase(e.getMessage()), + TestResource.getResource("R_unexpectedException")); + assertTrue("The query has timed out.".equalsIgnoreCase(e.getMessage()), + TestResource.getResource("R_unexpectedException")); + } + elapsedMillis += System.currentTimeMillis(); + if (elapsedMillis >= 3000) { + assertEquals(2000, (int) elapsedMillis, TestResource.getResource("R_executionTooLong")); + } - // Second execution: - // Verify connection is still usable. - // Verify execution with no timeout doesn't return too soon. - ps.setQueryTimeout(0); - elapsedMillis = -System.currentTimeMillis(); - ps.execute(); - elapsedMillis += System.currentTimeMillis(); + // Second execution: + // Verify connection is still usable. + // Verify execution with no timeout doesn't return too soon. + ps.setQueryTimeout(0); + elapsedMillis = -System.currentTimeMillis(); + ps.execute(); + elapsedMillis += System.currentTimeMillis(); - // Oddly enough, the server's idea of 7 seconds is actually slightly less than - // 7000 milliseconds by our clock (!) so we have to allow some slack here. - if (elapsedMillis < 6500) { - assertEquals(6500, (int) elapsedMillis, TestResource.getResource("R_executionNotLong")); + // Oddly enough, the server's idea of 7 seconds is actually slightly less than + // 7000 milliseconds by our clock (!) so we have to allow some slack here. + if (elapsedMillis < 6500) { + assertEquals(6500, (int) elapsedMillis, TestResource.getResource("R_executionNotLong")); + } } - - ps.close(); - con.close(); } /** @@ -224,51 +217,52 @@ public void testQueryTimeout() throws Exception { public void testCancelLongResponse() throws Exception { assumeTrue("JDBC42".equals(Utils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY); - ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con + .createStatement(SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { + ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); - throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { - } + throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); - ResultSet rs = stmt - .executeQuery("SELECT " + "a.col1, a.col2 FROM " + tableName + " a CROSS JOIN " + tableName + " b"); + } - // Scan the first MIN_TABLE_ROWS rows - int numSelectedRows = 0; - while (rs.next() && ++numSelectedRows < MIN_TABLE_ROWS); + try (ResultSet rs = stmt.executeQuery( + "SELECT " + "a.col1, a.col2 FROM " + tableName + " a CROSS JOIN " + tableName + " b")) { - // Verify that MIN_TABLE_ROWS rows were returned - // Wrong number of rows returned in first scan - assertEquals(MIN_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); + // Scan the first MIN_TABLE_ROWS rows + int numSelectedRows = 0; + while (rs.next() && ++numSelectedRows < MIN_TABLE_ROWS); - // Cancel the statement and verify that the ResultSet - // does NOT return all the remaining rows. - stmt.cancel(); + // Verify that MIN_TABLE_ROWS rows were returned + // Wrong number of rows returned in first scan + assertEquals(MIN_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); - try { - while (rs.next()) - ++numSelectedRows; + // Cancel the statement and verify that the ResultSet + // does NOT return all the remaining rows. + stmt.cancel(); - assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertEquals(TestResource.getResource("R_queryCancelled"), - TestResource.getResource("R_unexpectedException")); - } + try { + while (rs.next()) + ++numSelectedRows; - assertEquals(false, NUM_TABLE_ROWS * NUM_TABLE_ROWS == numSelectedRows, "All rows returned after cancel"); + assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertEquals(TestResource.getResource("R_queryCancelled"), + TestResource.getResource("R_unexpectedException")); + } - rs.close(); - assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + assertEquals(false, NUM_TABLE_ROWS * NUM_TABLE_ROWS == numSelectedRows, + "All rows returned after cancel"); - con.close(); + rs.close(); + assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + } + } } /** @@ -659,46 +653,46 @@ public void testCancelGetOutParams() throws Exception { // so that cancelling execution from the same thread will work. String name = RandomUtil.getIdentifier("p1"); final String procName = AbstractSQLGenerator.escapeIdentifier(name); - Connection con = DriverManager.getConnection(connectionString + ";packetSize=512"); - Statement stmt = con.createStatement(); - - try { - Utils.dropProcedureIfExists(procName, stmt); - } catch (Exception ex) {} ; - stmt.executeUpdate("CREATE PROCEDURE " + procName + " @arg1 CHAR(512) OUTPUT, " - + " @arg2 CHAR(512) OUTPUT, " + " @arg3 CHAR(512) OUTPUT " + "AS " + "BEGIN " - + " SET @arg1='hi' " + " SET @arg2='there' " + " SET @arg3='!' " + "END"); - CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?, ?)}"); - ((SQLServerStatement) cstmt).setResponseBuffering("adaptive"); - cstmt.registerOutParameter(1, Types.CHAR); - cstmt.registerOutParameter(2, Types.CHAR); - cstmt.registerOutParameter(3, Types.CHAR); - - // Cancel before getting any OUT params - cstmt.execute(); - cstmt.cancel(); - - // Cancel after getting first OUT param - cstmt.execute(); - cstmt.getString(1); - cstmt.cancel(); - - // Cancel after getting last OUT param - cstmt.execute(); - cstmt.getString(3); - cstmt.cancel(); - - // Cancel after getting OUT params out of order - cstmt.execute(); - cstmt.getString(2); - cstmt.getString(1); - cstmt.cancel(); + try (Connection con = DriverManager.getConnection(connectionString + ";packetSize=512"); + Statement stmt = con.createStatement()) { - // Reexecute to prove CS is still good after last cancel - cstmt.execute(); + try { + Utils.dropProcedureIfExists(procName, stmt); + } catch (Exception ex) {} ; + stmt.executeUpdate("CREATE PROCEDURE " + procName + " @arg1 CHAR(512) OUTPUT, " + + " @arg2 CHAR(512) OUTPUT, " + " @arg3 CHAR(512) OUTPUT " + "AS " + "BEGIN " + + " SET @arg1='hi' " + " SET @arg2='there' " + " SET @arg3='!' " + "END"); + CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?, ?)}"); + ((SQLServerStatement) cstmt).setResponseBuffering("adaptive"); + cstmt.registerOutParameter(1, Types.CHAR); + cstmt.registerOutParameter(2, Types.CHAR); + cstmt.registerOutParameter(3, Types.CHAR); + + // Cancel before getting any OUT params + cstmt.execute(); + cstmt.cancel(); + + // Cancel after getting first OUT param + cstmt.execute(); + cstmt.getString(1); + cstmt.cancel(); + + // Cancel after getting last OUT param + cstmt.execute(); + cstmt.getString(3); + cstmt.cancel(); + + // Cancel after getting OUT params out of order + cstmt.execute(); + cstmt.getString(2); + cstmt.getString(1); + cstmt.cancel(); + + // Reexecute to prove CS is still good after last cancel + cstmt.execute(); - Utils.dropProcedureIfExists(procName, stmt); - con.close(); + Utils.dropProcedureIfExists(procName, stmt); + } } static final int RUN_TIME_MILLIS = 10000; @@ -761,8 +755,7 @@ void start(final Connection con) { public void run() { ++numExecuteTries; - try { - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { while (rs.next()) ++numExecuteSuccesses; @@ -887,50 +880,46 @@ void stop() { @Test public void testIsCloseOnCompletion() throws Exception { - Connection con = DriverManager.getConnection(connectionString); + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement ps = con.prepareStatement("")) { - PreparedStatement ps = con.prepareStatement(""); + boolean result = false; + try { + result = ps.isCloseOnCompletion(); + } catch (Exception e) { - boolean result = false; - try { - result = ps.isCloseOnCompletion(); - } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); - throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); + } + assertEquals(false, result, "isCloseOnCompletion: " + TestResource.getResource("R_incorrectDefault")); } - - assertEquals(false, result, "isCloseOnCompletion: " + TestResource.getResource("R_incorrectDefault")); - - ps.close(); - con.close(); } @Test public void testCloseOnCompletion() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - PreparedStatement ps = con.prepareStatement("select ?"); - ps.setInt(1, 1); - - // enable isCloseOnCompletion - try { - ps.closeOnCompletion(); - } catch (Exception e) { - throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement ps = con.prepareStatement("select ?")) { + ps.setInt(1, 1); - } + // enable isCloseOnCompletion + try { + ps.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); - ResultSet rs; - try { - rs = ps.executeQuery(); - rs.close(); - } catch (SQLException e) { - log.fine("testIsCloseOnCompletion threw: " + e.getMessage()); - } + } - assertEquals(ps.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + ResultSet rs; + try { + rs = ps.executeQuery(); + rs.close(); + } catch (SQLException e) { + log.fine("testIsCloseOnCompletion threw: " + e.getMessage()); + } - con.close(); + assertEquals(ps.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + } } } @@ -948,25 +937,21 @@ public class TCStatement { */ @Test public void testIsCloseOnCompletion() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - assertEquals(false, stmt.isCloseOnCompletion(), "isCloseOnCompletion default should be false."); + assertEquals(false, stmt.isCloseOnCompletion(), "isCloseOnCompletion default should be false."); - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - - throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); + } + assertEquals(true, stmt.isCloseOnCompletion(), + "isCloseOnCompletion " + TestResource.getResource("R_shouldBeEnabled")); } - - assertEquals(true, stmt.isCloseOnCompletion(), - "isCloseOnCompletion " + TestResource.getResource("R_shouldBeEnabled")); - - stmt.close(); - con.close(); } /** @@ -974,28 +959,26 @@ public void testIsCloseOnCompletion() throws Exception { */ @Test public void testCloseOnCompletion() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - - throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { - } + throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); - ResultSet rs; - rs = stmt.executeQuery("SELECT 1"); - assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); + } - // now statement should be closed - rs.close(); + try (ResultSet rs = stmt.executeQuery("SELECT 1")) { + assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); - assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + // now statement should be closed + rs.close(); - con.close(); + assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + } + } } /** @@ -1005,37 +988,29 @@ public void testCloseOnCompletion() throws Exception { */ @Test public void testConsecutiveQueries() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); + } - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - - // enable isCloseOnCompletion - - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - throw new SQLException(TestResource.getResource("R_unexpectedException") + ": ", e); - } - - try { - Utils.dropTableIfExists(table1Name, stmt); - } catch (SQLException e) {} - try { - Utils.dropTableIfExists(table2Name, stmt); - } catch (SQLException e) {} - - stmt.executeUpdate("CREATE TABLE " + table1Name + " (col1 INT PRIMARY KEY)"); - stmt.executeUpdate("CREATE TABLE " + table2Name + " (col1 INT PRIMARY KEY)"); + try { + Utils.dropTableIfExists(table1Name, stmt); + } catch (SQLException e) {} + try { + Utils.dropTableIfExists(table2Name, stmt); + } catch (SQLException e) {} - ResultSet rs1 = stmt.executeQuery("SELECT * FROM " + table1Name); + stmt.executeUpdate("CREATE TABLE " + table1Name + " (col1 INT PRIMARY KEY)"); + stmt.executeUpdate("CREATE TABLE " + table2Name + " (col1 INT PRIMARY KEY)"); - try { - ResultSet rs2 = stmt.executeQuery("SELECT * FROM " + table2Name); - } catch (Exception e) { - assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + table2Name)) {} catch (Exception e) { + assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + } } - - con.close(); } /** @@ -1049,31 +1024,24 @@ public void testLargeMaxRowsJDBC41() throws Exception { assumeTrue("JDBC41".equals(Utils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - Connection con = DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); - - // testing exception for getLargeMaxRows method - try { - - stmt.getLargeMaxRows(); - throw new SQLException(TestResource.getResource("R_unexpectedException")); - } catch (Exception e) { - fail(e.getMessage()); - } + try (Connection con = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { - // testing exception for setLargeMaxRows method - try { - stmt.setLargeMaxRows(2015); - throw new SQLException(TestResource.getResource("R_unexpectedException")); - } catch (Exception e) { - fail(e.getMessage()); - } + // testing exception for getLargeMaxRows method + try { + stmt.getLargeMaxRows(); + throw new SQLException(TestResource.getResource("R_unexpectedException")); + } catch (Exception e) { + fail(e.getMessage()); + } - if (null != stmt) { - stmt.close(); - } - if (null != con) { - con.close(); + // testing exception for setLargeMaxRows method + try { + stmt.setLargeMaxRows(2015); + throw new SQLException(TestResource.getResource("R_unexpectedException")); + } catch (Exception e) { + fail(e.getMessage()); + } } } @@ -1086,49 +1054,44 @@ public void testLargeMaxRowsJDBC41() throws Exception { public void testLargeMaxRowsJDBC42() throws Exception { assumeTrue("JDBC42".equals(Utils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - Connection dbcon = DriverManager.getConnection(connectionString); - Statement dbstmt = dbcon.createStatement(); - - // Default value should return zero - long actual = dbstmt.getLargeMaxRows(); - assertEquals(actual, (long) 0, "getLargeMaxRows():" + TestResource.getResource("R_incorrectDefault")); - - // Set a new value less than MAX_VALUE, and then get the modified value - long newValue = 2012L; - dbstmt.setLargeMaxRows(newValue); - actual = dbstmt.getLargeMaxRows(); - assertEquals(actual, newValue, "LargeMaxRows() : set/get problem"); - - // Set a new value grater than MAX_VALUE, and then get the modified value - // SQL Server only supports integer limits for setting max rows - // If the value MAX_VALUE + 1 is accepted, throw exception - try { - newValue = (long) Integer.MAX_VALUE + 1; - dbstmt.setLargeMaxRows(newValue); - throw new SQLException("setLargeMaxRows(): Long values should not be set"); - } catch (Exception e) { - assertEquals( - ("calling setLargeMaxRows failed : java.lang.UnsupportedOperationException: " - + "The supported maximum row count for a result set is Integer.MAX_VALUE or less."), - (e.getMessage()), TestResource.getResource("R_unexpectedException")); - } - // Set a negative value. If negative is accepted, throw exception - try { - dbstmt.setLargeMaxRows(-2012L); - throw new SQLException("setLargeMaxRows(): Negative value not allowed"); - } catch (Exception e) { - assertEquals( - "calling setLargeMaxRows failed : com.microsoft.sqlserver.jdbc.SQLServerException: " - + "The maximum row count -2,012 for a result set must be non-negative.", - e.getMessage(), TestResource.getResource("R_unexpectedException")); - } + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - if (null != dbstmt) { - dbstmt.close(); - } - if (null != dbcon) { - dbcon.close(); + // Default value should return zero + long actual = stmt.getLargeMaxRows(); + assertEquals(actual, (long) 0, "getLargeMaxRows():" + TestResource.getResource("R_incorrectDefault")); + + // Set a new value less than MAX_VALUE, and then get the modified value + long newValue = 2012L; + stmt.setLargeMaxRows(newValue); + actual = stmt.getLargeMaxRows(); + assertEquals(actual, newValue, "LargeMaxRows() : set/get problem"); + + // Set a new value grater than MAX_VALUE, and then get the modified value + // SQL Server only supports integer limits for setting max rows + // If the value MAX_VALUE + 1 is accepted, throw exception + try { + newValue = (long) Integer.MAX_VALUE + 1; + stmt.setLargeMaxRows(newValue); + throw new SQLException("setLargeMaxRows(): Long values should not be set"); + } catch (Exception e) { + assertEquals( + ("calling setLargeMaxRows failed : java.lang.UnsupportedOperationException: " + + "The supported maximum row count for a result set is Integer.MAX_VALUE or less."), + (e.getMessage()), TestResource.getResource("R_unexpectedException")); + } + + // Set a negative value. If negative is accepted, throw exception + try { + stmt.setLargeMaxRows(-2012L); + throw new SQLException("setLargeMaxRows(): Negative value not allowed"); + } catch (Exception e) { + assertEquals( + "calling setLargeMaxRows failed : com.microsoft.sqlserver.jdbc.SQLServerException: " + + "The maximum row count -2,012 for a result set must be non-negative.", + e.getMessage(), TestResource.getResource("R_unexpectedException")); + } } } @@ -1318,8 +1281,8 @@ public class TCStatementParam { @Test public void testStatementOutParamGetsTwice() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { // enable isCloseOnCompletion try { @@ -1338,6 +1301,7 @@ public void testStatementOutParamGetsTwice() throws Exception { } else { assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); } + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); @@ -1357,33 +1321,36 @@ public void testStatementOutParamGetsTwice() throws Exception { } else { assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); } + } } @Test public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - 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 " + procNameTemp + " (?,?, ?, ?)}"); - cstmt.registerOutParameter(1, Types.INTEGER); - cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); - cstmt.registerOutParameter(3, Types.SMALLINT); - cstmt.setObject(4, Short.valueOf("23"), Types.SMALLINT); - cstmt.registerOutParameter(5, Types.INTEGER); - cstmt.execute(); - assertEquals(cstmt.getInt(1), 33, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(5), 23, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(3), 32, TestResource.getResource("R_valueNotMatch")); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + 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"); + + try (CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?, ?, ?)}")) { + cstmt.registerOutParameter(1, Types.INTEGER); + cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); + cstmt.registerOutParameter(3, Types.SMALLINT); + cstmt.setObject(4, Short.valueOf("23"), Types.SMALLINT); + cstmt.registerOutParameter(5, Types.INTEGER); + cstmt.execute(); + assertEquals(cstmt.getInt(1), 33, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(5), 23, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(3), 32, TestResource.getResource("R_valueNotMatch")); - cstmt.setObject(2, Short.valueOf("34"), Types.SMALLINT); - cstmt.setObject(4, Short.valueOf("24"), Types.SMALLINT); - cstmt.execute(); - assertEquals(cstmt.getInt(3), 34, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(5), 24, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(1), 35, TestResource.getResource("R_valueNotMatch")); + cstmt.setObject(2, Short.valueOf("34"), Types.SMALLINT); + cstmt.setObject(4, Short.valueOf("24"), Types.SMALLINT); + cstmt.execute(); + assertEquals(cstmt.getInt(3), 34, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(5), 24, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(1), 35, TestResource.getResource("R_valueNotMatch")); + } + } } /** @@ -1394,24 +1361,26 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { @Test public void testStatementOutParamGetsTwiceInOut() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - 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 " + procNameTemp + " (?,?)}"); - cstmt.registerOutParameter(1, Types.INTEGER); - cstmt.setObject(2, Short.valueOf("1"), Types.SMALLINT); - cstmt.setObject(3, Short.valueOf("100"), Types.SMALLINT); - cstmt.registerOutParameter(3, Types.SMALLINT); - cstmt.execute(); - assertEquals(cstmt.getInt(1), 2, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(1), 2, TestResource.getResource("R_valueNotMatch")); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + 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"); + + try (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); + cstmt.registerOutParameter(3, Types.SMALLINT); + cstmt.execute(); + assertEquals(cstmt.getInt(1), 2, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(1), 2, TestResource.getResource("R_valueNotMatch")); - cstmt.setObject(2, Short.valueOf("10"), Types.SMALLINT); - cstmt.execute(); - assertEquals(cstmt.getInt(1), 11, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(3), 101, TestResource.getResource("R_valueNotMatch")); + cstmt.setObject(2, Short.valueOf("10"), Types.SMALLINT); + cstmt.execute(); + assertEquals(cstmt.getInt(1), 11, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(3), 101, TestResource.getResource("R_valueNotMatch")); + } + } } /** @@ -1422,25 +1391,27 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { @Test public void testResultSetParams() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - 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')"); - String query = "create procedure " + procName - + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + tableName - + " where col1=@col1Value SET @col2Value='hi' END"; - stmt.execute(query); - - CallableStatement cstmt = conn.prepareCall("{call " + procName + "(?, ?)}"); - cstmt.setInt(1, 0); - cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); - ResultSet rs = cstmt.executeQuery(); - rs.next(); - assertEquals(rs.getString(2), "hello", TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getString(2), "hi", TestResource.getResource("R_valueNotMatch")); + 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')"); + String query = "create procedure " + procName + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + tableName + + " where col1=@col1Value SET @col2Value='hi' END"; + stmt.execute(query); + + try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + cstmt.setInt(1, 0); + cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); + ResultSet rs = cstmt.executeQuery(); + rs.next(); + assertEquals(rs.getString(2), "hello", TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getString(2), "hi", TestResource.getResource("R_valueNotMatch")); + } + } } /** @@ -1451,26 +1422,28 @@ public void testResultSetParams() throws Exception { @Test public void testResultSetNullParams() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - 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')"); - String query = "create procedure " + procName - + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + tableName - + " where col1=@col1Value SET @col2Value='hi' END"; - stmt.execute(query); - - CallableStatement cstmt = conn.prepareCall("{call " + procName + "(?, ?)}"); - cstmt.setInt(1, 0); - try { - cstmt.getInt(2); - } catch (Exception ex) { - if (!ex.getMessage().equalsIgnoreCase("The output parameter 2 was not registered for output.")) - throw 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')"); + String query = "create procedure " + procName + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + tableName + + " where col1=@col1Value SET @col2Value='hi' END"; + stmt.execute(query); + + try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + cstmt.setInt(1, 0); + try { + cstmt.getInt(2); + } catch (Exception ex) { + if (!ex.getMessage().equalsIgnoreCase("The output parameter 2 was not registered for output.")) + throw ex; + } + } + } } /** @@ -1480,27 +1453,28 @@ public void testResultSetNullParams() throws Exception { @Test public void testFailedToResumeTransaction() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); - stmt.executeUpdate("Insert into " + tableName + " values(0)"); - stmt.executeUpdate("Insert into " + tableName + " values(1)"); - stmt.executeUpdate("Insert into " + tableName + " values(2)"); - stmt.executeUpdate("Insert into " + tableName + " values(3)"); - PreparedStatement ps = conn - .prepareStatement("BEGIN TRAN " + "Insert into " + tableName + " values(4) " + "ROLLBACK"); + stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); + stmt.executeUpdate("Insert into " + tableName + " values(0)"); + stmt.executeUpdate("Insert into " + tableName + " values(1)"); + stmt.executeUpdate("Insert into " + tableName + " values(2)"); + stmt.executeUpdate("Insert into " + tableName + " values(3)"); + PreparedStatement ps = con + .prepareStatement("BEGIN TRAN " + "Insert into " + tableName + " values(4) " + "ROLLBACK"); - conn.setAutoCommit(false); - PreparedStatement ps2 = conn.prepareStatement("Insert into " + tableName + " values('a')"); + con.setAutoCommit(false); + try (PreparedStatement ps2 = con.prepareStatement("Insert into " + tableName + " values('a')")) { - try { - ps2.execute(); - } catch (SQLException e) {} - try { - stmt.executeUpdate("Insert into " + tableName + " values(4)"); - } catch (SQLException ex) {} - conn.close(); + try { + ps2.execute(); + } catch (SQLException e) {} + try { + stmt.executeUpdate("Insert into " + tableName + " values(4)"); + } catch (SQLException ex) {} + } + } } /** @@ -1510,26 +1484,26 @@ public void testFailedToResumeTransaction() throws Exception { @Test public void testResultSetErrors() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - 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')"); - String query = "create procedure " + procName - + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from somenonexistanttable where col1=@col1Value SET @col2Value='hi' END"; - stmt.execute(query); + 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')"); + String query = "create procedure " + procName + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from somenonexistanttable where col1=@col1Value SET @col2Value='hi' END"; + stmt.execute(query); - CallableStatement cstmt = conn.prepareCall("{call " + procName + "(?, ?)}"); - cstmt.setInt(1, 0); - cstmt.registerOutParameter(2, Types.VARCHAR); + try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + cstmt.setInt(1, 0); + cstmt.registerOutParameter(2, Types.VARCHAR); - try { - ResultSet rs = cstmt.executeQuery(); - } catch (Exception ex) {} ; + try (ResultSet rs = cstmt.executeQuery()) {} catch (Exception ex) {} ; - assertEquals(null, cstmt.getString(2), TestResource.getResource("R_valueNotMatch")); + assertEquals(null, cstmt.getString(2), TestResource.getResource("R_valueNotMatch")); + } + } } /** @@ -1540,96 +1514,92 @@ public void testResultSetErrors() throws Exception { // 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(); - - stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); - stmt.executeUpdate("insert into " + tableName + " values(0)"); - stmt.executeUpdate("insert into " + tableName + " values(1)"); - stmt.executeUpdate("insert into " + tableName + " values(2)"); - stmt.execute("create procedure " + procName + " @col1Value int AS " + " BEGIN " + " SELECT col1 FROM " - + tableName + " WITH (UPDLOCK) WHERE (col1 = @col1Value) " + " END"); - - // For the test, lock each row in the table, one by one, for update - // on one connection and, on another connection, verify that the - // row is locked by looking for an expected row error for that row. - // The expectation is that ResultSet.next() will throw an lock timeout - // exception when the locked row is encountered, no matter whether the - // locked row is the first one in the table or not. Also, the connection - // must be usable after properly handling and dispatching the row locked - // error. - - for (int row = 0; row <= 2; row++) { - // On the first connection, retrieve the indicated row, - // locking it for update. - Connection testConn1 = DriverManager.getConnection(connectionString); - testConn1.setAutoCommit(false); - CallableStatement cstmt = testConn1.prepareCall("{call " + procName + "(?)}"); - cstmt.setInt(1, row); - - // enable isCloseOnCompletion - try { - cstmt.closeOnCompletion(); - } catch (Exception e) { - throw new SQLException(TestResource.getResource("R_unexpectedException")); - } - - ResultSet rs = cstmt.executeQuery(); - assertEquals(true, rs.next(), "Query returned no rows"); - rs.close(); - assertEquals(cstmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); - - // On a second connection, repeat the query, with an immediate - // lock timeout to induce an error. - Connection testConn2 = DriverManager.getConnection(connectionString); - testConn2.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - testConn2.setAutoCommit(false); - Statement stmt2 = testConn2.createStatement(); - stmt2.executeUpdate("SET LOCK_TIMEOUT 0"); - - CallableStatement cstmt2 = testConn2.prepareCall("SELECT col1 FROM " + tableName + " WITH (UPDLOCK)"); - - // Verify that the result set can be closed after - // the lock timeout error - rs = cstmt2.executeQuery(); - rs.close(); + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - // Verify that the ResultSet hits a lock timeout exception on the - // indicated row and continues to report that exception on subsequent - // accesses to that row. - rs = cstmt2.executeQuery(); - for (int i = 0; i < row; i++) - assertEquals(true, rs.next(), "Query returned wrong number of rows."); + stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); + stmt.executeUpdate("insert into " + tableName + " values(0)"); + stmt.executeUpdate("insert into " + tableName + " values(1)"); + stmt.executeUpdate("insert into " + tableName + " values(2)"); + stmt.execute( + "create procedure " + procName + " @col1Value int AS " + " BEGIN " + " SELECT col1 FROM " + + tableName + " WITH (UPDLOCK) WHERE (col1 = @col1Value) " + " END"); + + // For the test, lock each row in the table, one by one, for update + // on one connection and, on another connection, verify that the + // row is locked by looking for an expected row error for that row. + // The expectation is that ResultSet.next() will throw an lock timeout + // exception when the locked row is encountered, no matter whether the + // locked row is the first one in the table or not. Also, the connection + // must be usable after properly handling and dispatching the row locked + // error. + + for (int row = 0; row <= 2; row++) { + // On the first connection, retrieve the indicated row, + // locking it for update. + try (Connection testConn1 = DriverManager.getConnection(connectionString)) { + testConn1.setAutoCommit(false); + try (CallableStatement cstmt = testConn1.prepareCall("{call " + procName + "(?)}")) { + cstmt.setInt(1, row); + + // enable isCloseOnCompletion + try { + cstmt.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException")); + } - for (int i = 0; i < 2; i++) { - try { - rs.next(); - assertEquals(false, true, - "lock timeout" + TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertEquals(1222, // lock timeout - e.getErrorCode(), TestResource.getResource("R_unexpectedException") + e.getMessage()); + try (ResultSet rs = cstmt.executeQuery()) { + assertEquals(true, rs.next(), "Query returned no rows"); + } + assertEquals(cstmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + + // On a second connection, repeat the query, with an immediate + // lock timeout to induce an error. + try (Connection testConn2 = DriverManager.getConnection(connectionString)) { + testConn2.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + testConn2.setAutoCommit(false); + try (Statement stmt2 = testConn2.createStatement()) { + stmt2.executeUpdate("SET LOCK_TIMEOUT 0"); + + try (CallableStatement cstmt2 = testConn2 + .prepareCall("SELECT col1 FROM " + tableName + " WITH (UPDLOCK)")) { + + // Verify that the result set can be closed after + // the lock timeout error + try (ResultSet rs = cstmt2.executeQuery()) { + rs.close(); + } + // Verify that the ResultSet hits a lock timeout exception on the + // indicated row and continues to report that exception on subsequent + // accesses to that row. + try (ResultSet rs = cstmt2.executeQuery()) { + for (int i = 0; i < row; i++) + assertEquals(true, rs.next(), "Query returned wrong number of rows."); + + for (int i = 0; i < 2; i++) { + try { + rs.next(); + assertEquals(false, true, "lock timeout" + + TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertEquals(1222, // lock timeout + e.getErrorCode(), + TestResource.getResource("R_unexpectedException") + + e.getMessage()); + } + } + } + } + + // Verify testConn2 is still usable for queries + stmt2.executeQuery("SELECT 1").close(); + } + } + } } } - - rs.close(); - - // Closing the callable statement after the error - // has been handled should not throw any exception. - cstmt2.close(); - - // Verify testConn2 is still usable for queries - stmt2.executeQuery("SELECT 1").close(); - - // Now clean up - stmt2.close(); - testConn2.close(); - testConn1.close(); } - stmt.close(); - conn.close(); } @AfterEach diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java index e8f44c66f..86f1fe7b3 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java @@ -133,10 +133,8 @@ public void wrapTest() throws Exception { @Test public void unWrapFailureTest() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection con = DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); - - try { + try (Connection con = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String str = "java.lang.String"; boolean isWrapper = stmt.isWrapperFor(Class.forName(str)); stmt.unwrap(Class.forName(str)); @@ -152,21 +150,13 @@ public void unWrapFailureTest() throws Exception { "isWrapperFor " + TestResource.getResource("R_shouldBeSupported")); assertEquals(e.getMessage(), "This operation is not supported.", TestResource.getResource("R_unexpectedExceptionContent")); - } finally { - if (null != stmt) { - stmt.close(); - } - if (null != con) { - con.close(); - } } } private static boolean isKatmaiServer() throws Exception { - DBConnection conn = new DBConnection(connectionString); - double version = conn.getServerVersion(); - conn.close(); - return ((version >= 10.0) ? true : false); + try (DBConnection conn = new DBConnection(connectionString)) { + double version = conn.getServerVersion(); + return ((version >= 10.0) ? true : false); + } } - } From 893d09e69554e5533620a83dcdecadd9e47bd20a Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Thu, 30 Aug 2018 14:28:54 -0700 Subject: [PATCH 02/15] resolved conflict --- .../jdbc/databasemetadata/DatabaseMetaDataTest.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index e5ee1e258..43cd73704 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -108,11 +108,7 @@ public void testDriverVersion() throws SQLException, IOException { int intBuildVersion = Integer.valueOf(buildVersion); int intDriverVersion = Integer.valueOf(driverVersion); - if (isSnapshot) { - assertTrue(intDriverVersion < intBuildVersion, TestResource.getResource("R_buildVersionError")); - } else { - assertTrue(intDriverVersion == intBuildVersion, TestResource.getResource("R_buildVersionError")); - } + assertTrue(intDriverVersion == intBuildVersion, TestResource.getResource("R_buildVersionError")); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } From ded037bd74a6b13dcd402881482e37551f2e6867 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Thu, 30 Aug 2018 15:06:12 -0700 Subject: [PATCH 03/15] fixed typo --- .../sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index 2ca1612e5..c326e4098 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -108,6 +108,7 @@ public void testDriverVersion() throws SQLException, IOException { int intBuildVersion = Integer.valueOf(buildVersion); int intDriverVersion = Integer.valueOf(driverVersion); assertTrue(intDriverVersion == intBuildVersion, TestResource.getResource("R_buildVersionError")); + } } /** From 7d79eeaa371b2160c33d3b6c8b2ffd5a087fe4d1 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Thu, 30 Aug 2018 16:08:50 -0700 Subject: [PATCH 04/15] fixes --- .../jdbc/connection/RequestBoundaryMethodsTest.java | 6 ++++-- .../jdbc/preparedStatement/BatchExecutionWithNullTest.java | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java index c6ea0df75..c3b9b721a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -278,8 +278,10 @@ public void testStatements() throws SQLException { if (null != cs) { cs.close(); } - try (SQLServerConnection con = connect(); Statement st = con.createStatement()) { - Utils.dropTableIfExists(tableName, st); + if (null != tableName) { + try (SQLServerConnection con = connect(); Statement st = con.createStatement()) { + Utils.dropTableIfExists(tableName, st); + } } } } 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 f44c8bfe3..5efe55448 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -119,7 +119,8 @@ public void testSetup() throws TestAbortedException, Exception { @AfterAll public static void terminateVariation() throws SQLException { - try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + try (Connection cnnection = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { Utils.dropTableIfExists("esimple", stmt); } From bdea8144e60d41ef93028912b902a502c2bc05c5 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Thu, 30 Aug 2018 16:23:12 -0700 Subject: [PATCH 05/15] fixes --- .../jdbc/preparedStatement/BatchExecutionWithNullTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 5efe55448..caafbabbc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -119,7 +119,7 @@ public void testSetup() throws TestAbortedException, Exception { @AfterAll public static void terminateVariation() throws SQLException { - try (Connection cnnection = DriverManager.getConnection(connectionString); + try (Connection conn = DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { Utils.dropTableIfExists("esimple", stmt); } From a50d51394f6fbb5964134f558b6e682fd6894fa6 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Thu, 30 Aug 2018 16:50:28 -0700 Subject: [PATCH 06/15] fixed --- .../microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java | 5 +++-- .../jdbc/connection/RequestBoundaryMethodsTest.java | 6 ++++-- .../jdbc/preparedStatement/BatchExecutionWithNullTest.java | 5 +++-- 3 files changed, 10 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 42552b5ff..276c55683 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -84,8 +84,9 @@ public class AESetup extends AbstractTest { */ @BeforeAll public static void setUpConnection() throws TestAbortedException, Exception { - assumeTrue(13 <= new DBConnection(connectionString).getServerVersion(), - TestResource.getResource("R_Incompat_SQLServerVersion")); + try (DBConnection con = new DBConnection(connectionString)) { + assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); + } String AETestConenctionString = connectionString + ";sendTimeAsDateTime=false"; readFromFile(javaKeyStoreInputFile, "Alias name"); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java index c3b9b721a..a12588dbd 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -12,7 +12,9 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.sql.Connection; import java.sql.CallableStatement; +import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -279,8 +281,8 @@ public void testStatements() throws SQLException { cs.close(); } if (null != tableName) { - try (SQLServerConnection con = connect(); Statement st = con.createStatement()) { - Utils.dropTableIfExists(tableName, st); + try (Connection con = DriverManager.getConnection(connectionString); Statement statement = con.createStatement()) { + Utils.dropTableIfExists(tableName, statement); } } } 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 caafbabbc..5d3f9cc77 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -106,8 +106,9 @@ public void testAddbatch2AEOnConnection() throws SQLException { @BeforeEach public void testSetup() throws TestAbortedException, Exception { - assumeTrue(13 <= new DBConnection(connectionString).getServerVersion(), - TestResource.getResource("R_Incompat_SQLServerVersion")); + try (DBConnection con = new DBConnection(connectionString)) { + assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); + } connection = DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) connection.createStatement(); From a6403512862bca368813fe0890030ca138e00a1e Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Thu, 30 Aug 2018 17:37:27 -0700 Subject: [PATCH 07/15] review comments --- .../jdbc/connection/PoolingTest.java | 15 +- .../jdbc/connection/TimeoutTest.java | 4 +- .../DatabaseMetaDataForeignKeyTest.java | 135 ++++---- .../DatabaseMetaDataTest.java | 304 ++++++++---------- 4 files changed, 193 insertions(+), 265 deletions(-) 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 fbfc0eb88..879bb7f1a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -85,23 +85,10 @@ public void testConnectionPoolReget() throws SQLException { PooledConnection pc = null; try { pc = ds.getPooledConnection(); - Connection con = null; - Connection con2 = null; - try { - con = pc.getConnection(); - - // now re-get a connection - con2 = pc.getConnection(); + try (Connection con = pc.getConnection(); Connection con2 = pc.getConnection()) { // assert that the first connection is closed. assertTrue(con.isClosed(), TestResource.getResource("R_firstConnectionNotClosed")); - } finally { - if (null != con) { - con.close(); - } - if (null != con2) { - con2.close(); - } } } finally { if (null != pc) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java index 28613d790..c29206c28 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java @@ -246,8 +246,8 @@ public void testSocketTimeout() throws Exception { assertEquals(e.getMessage(), TestResource.getResource("R_readTimedOut"), TestResource.getResource("R_invalidExceptionMessage")); } - try { - conn.createStatement().execute("SELECT @@version"); + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + stmt.execute("SELECT @@version"); } catch (SQLException e) { assertEquals(e.getMessage(), TestResource.getResource("R_connectionIsClosed"), TestResource.getResource("R_invalidExceptionMessage")); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java index 600757bb9..1ddfd947a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java @@ -95,40 +95,26 @@ public static void terminateVariation() throws SQLException { */ @Test public void testGetImportedKeys() throws SQLException { - SQLServerResultSet rs1 = null; - SQLServerResultSet rs2 = null; - SQLServerResultSet rs3 = null; - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) conn.getMetaData(); - rs1 = (SQLServerResultSet) dmd.getImportedKeys(null, null, table1); - validateGetImportedKeysResults(rs1); + try (SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getImportedKeys(null, null, table1); + SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getImportedKeys(catalog, schema, table1); + SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getImportedKeys(catalog, "", table1)) { - rs2 = (SQLServerResultSet) dmd.getImportedKeys(catalog, schema, table1); - validateGetImportedKeysResults(rs2); + validateGetImportedKeysResults(rs1); + validateGetImportedKeysResults(rs2); + validateGetImportedKeysResults(rs3); - rs3 = (SQLServerResultSet) dmd.getImportedKeys(catalog, "", table1); - validateGetImportedKeysResults(rs3); - - try { - dmd.getImportedKeys("", schema, table1); - fail(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + try { + dmd.getImportedKeys("", schema, table1); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + } } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - if (null != rs3) { - rs3.close(); - } } } @@ -173,9 +159,6 @@ public void testGetExportedKeys() throws SQLException { int[][] values = { // expected UPDATE_RULE, expected DELETE_RULE {4, 3}, {2, 0}, {0, 2}, {3, 4}}; - SQLServerResultSet rs1 = null; - SQLServerResultSet rs2 = null; - SQLServerResultSet rs3 = null; try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { @@ -183,40 +166,32 @@ public void testGetExportedKeys() throws SQLException { for (int i = 0; i < tableNames.length; i++) { String pkTable = tableNames[i]; - rs1 = (SQLServerResultSet) dmd.getExportedKeys(null, null, pkTable); - rs1.next(); - assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs1.getInt("DELETE_RULE")); - - rs2 = (SQLServerResultSet) dmd.getExportedKeys(catalog, schema, pkTable); - rs2.next(); - assertEquals(values[i][0], rs2.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs2.getInt("DELETE_RULE")); - - rs3 = (SQLServerResultSet) dmd.getExportedKeys(catalog, "", pkTable); - rs3.next(); - assertEquals(values[i][0], rs3.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs3.getInt("DELETE_RULE")); - - try { - dmd.getExportedKeys("", schema, pkTable); - fail(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + try (SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getExportedKeys(null, null, pkTable); + SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getExportedKeys(catalog, schema, pkTable); + SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getExportedKeys(catalog, "", pkTable)) { + + rs1.next(); + assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs1.getInt("DELETE_RULE")); + + rs2.next(); + assertEquals(values[i][0], rs2.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs2.getInt("DELETE_RULE")); + + rs3.next(); + assertEquals(values[i][0], rs3.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs3.getInt("DELETE_RULE")); + + try { + dmd.getExportedKeys("", schema, pkTable); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertTrue(e.getMessage().startsWith(TestResource.getResource("R_dbNameIsCurrentDB"))); + } } } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - if (null != rs3) { - rs3.close(); - } } } @@ -238,29 +213,31 @@ public void testGetCrossReference() throws SQLException { for (int i = 0; i < tableNames.length; i++) { String pkTable = tableNames[i]; - SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getCrossReference(null, null, pkTable, null, null, + try (SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getCrossReference(null, null, pkTable, null, null, fkTable); - rs1.next(); - assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs1.getInt("DELETE_RULE")); + SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getCrossReference(catalog, schema, pkTable, + catalog, schema, fkTable); + SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getCrossReference(catalog, "", pkTable, catalog, + "", fkTable)) { - SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getCrossReference(catalog, schema, pkTable, catalog, - schema, fkTable); - rs2.next(); - assertEquals(values[i][0], rs2.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs2.getInt("DELETE_RULE")); + rs1.next(); + assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs1.getInt("DELETE_RULE")); - SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getCrossReference(catalog, "", pkTable, catalog, "", - fkTable); - rs3.next(); - assertEquals(values[i][0], rs3.getInt("UPDATE_RULE")); - assertEquals(values[i][1], rs3.getInt("DELETE_RULE")); - - try { - dmd.getCrossReference("", schema, pkTable, "", schema, fkTable); - fail(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertEquals(TestResource.getResource("R_dbNameIsCurrentDB"), e.getMessage()); + rs2.next(); + assertEquals(values[i][0], rs2.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs2.getInt("DELETE_RULE")); + + rs3.next(); + assertEquals(values[i][0], rs3.getInt("UPDATE_RULE")); + assertEquals(values[i][1], rs3.getInt("DELETE_RULE")); + + try { + dmd.getCrossReference("", schema, pkTable, "", schema, fkTable); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertEquals(TestResource.getResource("R_dbNameIsCurrentDB"), e.getMessage()); + } } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index c326e4098..7a4547581 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -197,52 +197,46 @@ public void testDBSchemasForDashedCatalogName() throws SQLException { UUID id = UUID.randomUUID(); String testCatalog = "dash-catalog" + id; String testSchema = "some-schema" + id; - ResultSet rs = null; try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + Statement stmt = connection.createStatement()) { Utils.dropDatabaseIfExists(testCatalog, stmt); stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); stmt.execute(String.format("USE [%s]", testCatalog)); stmt.execute(String.format("CREATE SCHEMA [%s]", testSchema)); - rs = conn.getMetaData().getSchemas(testCatalog, null); - - MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[] schemaMsgArgs = {"Schema"}; - - boolean hasResults = false; - boolean hasDashCatalogSchema = false; - while (rs.next()) { - hasResults = true; - String schemaName = rs.getString(1); - assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); - String catalogName = rs.getString(2); - if (schemaName.equals(testSchema)) { - hasDashCatalogSchema = true; - assertEquals(catalogName, testCatalog); - } else { - assertNull(catalogName); + try (ResultSet rs = conn.getMetaData().getSchemas(testCatalog, null)) { + + MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[] schemaMsgArgs = {"Schema"}; + + boolean hasResults = false; + boolean hasDashCatalogSchema = false; + while (rs.next()) { + hasResults = true; + String schemaName = rs.getString(1); + assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); + String catalogName = rs.getString(2); + if (schemaName.equals(testSchema)) { + hasDashCatalogSchema = true; + assertEquals(catalogName, testCatalog); + } else { + assertNull(catalogName); + } } - } - MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); + MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); - MessageFormat dashCatalogFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - assertTrue(hasDashCatalogSchema, dashCatalogFormat.format(new Object[] {testSchema})); + MessageFormat dashCatalogFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + assertTrue(hasDashCatalogSchema, dashCatalogFormat.format(new Object[] {testSchema})); + } finally { + Utils.dropDatabaseIfExists(testCatalog, stmt); + } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != rs) { - rs.close(); - } - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { - Utils.dropDatabaseIfExists(testCatalog, stmt); - } } } @@ -258,7 +252,6 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { String testCatalog = "dash-catalog" + id; String testSchema = "some-schema" + id; - ResultSet rs = null; try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { Utils.dropDatabaseIfExists(testCatalog, stmt); stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); @@ -266,37 +259,31 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { stmt.execute(String.format("USE [%s]", testCatalog)); stmt.execute(String.format("CREATE SCHEMA [%s]", testSchema)); - rs = conn.getMetaData().getSchemas(testCatalog, "some-%"); - - MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[] schemaMsgArgs = {testSchema}; - Object[] catalogMsgArgs = {testCatalog}; + try (ResultSet rs = conn.getMetaData().getSchemas(testCatalog, "some-%")) { + + MessageFormat schemaEmptyFormat = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[] schemaMsgArgs = {testSchema}; + Object[] catalogMsgArgs = {testCatalog}; + + boolean hasResults = false; + while (rs.next()) { + hasResults = true; + String schemaName = rs.getString(1); + String catalogName = rs.getString(2); + assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); + assertTrue(!StringUtils.isEmpty(catalogName), schemaEmptyFormat.format(catalogMsgArgs)); + assertEquals(schemaName, schemaMsgArgs[0]); + assertEquals(catalogName, catalogMsgArgs[0]); + } - boolean hasResults = false; - while (rs.next()) { - hasResults = true; - String schemaName = rs.getString(1); - String catalogName = rs.getString(2); - assertTrue(!StringUtils.isEmpty(schemaName), schemaEmptyFormat.format(schemaMsgArgs)); - assertTrue(!StringUtils.isEmpty(catalogName), schemaEmptyFormat.format(catalogMsgArgs)); - assertEquals(schemaName, schemaMsgArgs[0]); - assertEquals(catalogName, catalogMsgArgs[0]); + MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); + } finally { + Utils.dropDatabaseIfExists(testCatalog, stmt); } - - MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != rs) { - rs.close(); - } - - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement()) { - Utils.dropDatabaseIfExists(testCatalog, stmt); - } } } @@ -312,30 +299,23 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { */ public void testDBTables() throws SQLException { - ResultSet rsCatalog = null; - ResultSet rs = null; try (Connection con = DriverManager.getConnection(connectionString)) { DatabaseMetaData databaseMetaData = con.getMetaData(); - rsCatalog = databaseMetaData.getCatalogs(); + try (ResultSet rsCatalog = databaseMetaData.getCatalogs()) { - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"catalog"}; - assertTrue(rsCatalog.next(), form1.format(msgArgs1)); + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"catalog"}; + assertTrue(rsCatalog.next(), form1.format(msgArgs1)); - String[] types = {"TABLE"}; - rs = databaseMetaData.getTables(rsCatalog.getString("TABLE_CAT"), null, "%", types); + String[] types = {"TABLE"}; + try (ResultSet rs = databaseMetaData.getTables(rsCatalog.getString("TABLE_CAT"), null, "%", types)) { - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[] msgArgs2 = {"Table"}; - while (rs.next()) { - assertTrue(!StringUtils.isEmpty(rs.getString("TABLE_NAME")), form2.format(msgArgs2)); - } - } finally { - if (null != rsCatalog) { - rsCatalog.close(); - } - if (null != rs) { - rs.close(); + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[] msgArgs2 = {"Table"}; + while (rs.next()) { + assertTrue(!StringUtils.isEmpty(rs.getString("TABLE_NAME")), form2.format(msgArgs2)); + } + } } } } @@ -353,49 +333,40 @@ public void testDBTables() throws SQLException { */ @Test public void testGetDBColumn() throws SQLException { - - ResultSet rs = null; - ResultSet rs1 = null; try (Connection conn = DriverManager.getConnection(connectionString)) { DatabaseMetaData databaseMetaData = conn.getMetaData(); String[] types = {"TABLE"}; - rs = databaseMetaData.getTables(null, null, "%", types); - - - // Fetch one table - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"table"}; - assertTrue(rs.next(), form1.format(msgArgs1)); - - // Go through all columns. - rs1 = databaseMetaData.getColumns(null, null, rs.getString("TABLE_NAME"), "%"); - - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"Data Type"}, {"Type"}, - {"Column Size"}, {"Nullable value"}, {"IS_NULLABLE"}, {"IS_AUTOINCREMENT"}}; - while (rs1.next()) { - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); - assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); - assertTrue(!StringUtils.isEmpty(rs1.getString("DATA_TYPE")), form2.format(msgArgs2[4])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TYPE_NAME")), form2.format(msgArgs2[5])); - assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_SIZE")), form2.format(msgArgs2[6])); - assertTrue(!StringUtils.isEmpty(rs1.getString("NULLABLE")), form2.format(msgArgs2[7])); // 11 - assertTrue(!StringUtils.isEmpty(rs1.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 18 - assertTrue(!StringUtils.isEmpty(rs1.getString("IS_AUTOINCREMENT")), form2.format(msgArgs2[9])); // 22 + try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) { + + // Fetch one table + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"table"}; + assertTrue(rs.next(), form1.format(msgArgs1)); + + // Go through all columns. + try (ResultSet rs1 = databaseMetaData.getColumns(null, null, rs.getString("TABLE_NAME"), "%")) { + + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"Data Type"}, {"Type"}, + {"Column Size"}, {"Nullable value"}, {"IS_NULLABLE"}, {"IS_AUTOINCREMENT"}}; + while (rs1.next()) { + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); + assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); + assertTrue(!StringUtils.isEmpty(rs1.getString("DATA_TYPE")), form2.format(msgArgs2[4])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TYPE_NAME")), form2.format(msgArgs2[5])); + assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_SIZE")), form2.format(msgArgs2[6])); + assertTrue(!StringUtils.isEmpty(rs1.getString("NULLABLE")), form2.format(msgArgs2[7])); // 11 + assertTrue(!StringUtils.isEmpty(rs1.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 18 + assertTrue(!StringUtils.isEmpty(rs1.getString("IS_AUTOINCREMENT")), form2.format(msgArgs2[9])); // 22 + } + } } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != rs) { - rs.close(); - } - if (null != rs1) { - rs1.close(); - } } } @@ -410,34 +381,34 @@ public void testGetDBColumn() throws SQLException { */ @Test public void testGetColumnPrivileges() throws SQLException { - - ResultSet rsTables = null; - ResultSet rs1 = null; - + try (Connection conn = DriverManager.getConnection(connectionString)) { DatabaseMetaData databaseMetaData = conn.getMetaData(); String[] types = {"TABLE"}; - rsTables = databaseMetaData.getTables(null, null, "%", types); - - // Fetch one table - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"table"}; - assertTrue(rsTables.next(), form1.format(msgArgs1)); - - rs1 = databaseMetaData.getColumnPrivileges(null, null, rsTables.getString("TABLE_NAME"), "%"); - - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); - Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"GRANTOR"}, {"GRANTEE"}, - {"PRIVILEGE"}, {"IS_GRANTABLE"}}; - while (rs1.next()) { - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); - assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); - assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); - assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTOR")), form2.format(msgArgs2[4])); - assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTEE")), form2.format(msgArgs2[5])); - assertTrue(!StringUtils.isEmpty(rs1.getString("PRIVILEGE")), form2.format(msgArgs2[6])); - assertTrue(!StringUtils.isEmpty(rs1.getString("IS_GRANTABLE")), form2.format(msgArgs2[7])); + try (ResultSet rsTables = databaseMetaData.getTables(null, null, "%", types)) { + + // Fetch one table + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"table"}; + assertTrue(rsTables.next(), form1.format(msgArgs1)); + + try (ResultSet rs1 = databaseMetaData.getColumnPrivileges(null, null, rsTables.getString("TABLE_NAME"), + "%")) { + + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameEmpty")); + Object[][] msgArgs2 = {{"Category"}, {"SCHEMA"}, {"Table"}, {"COLUMN"}, {"GRANTOR"}, {"GRANTEE"}, + {"PRIVILEGE"}, {"IS_GRANTABLE"}}; + while (rs1.next()) { + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_CAT")), form2.format(msgArgs2[0])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_SCHEM")), form2.format(msgArgs2[1])); + assertTrue(!StringUtils.isEmpty(rs1.getString("TABLE_NAME")), form2.format(msgArgs2[2])); + assertTrue(!StringUtils.isEmpty(rs1.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); + assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTOR")), form2.format(msgArgs2[4])); + assertTrue(!StringUtils.isEmpty(rs1.getString("GRANTEE")), form2.format(msgArgs2[5])); + assertTrue(!StringUtils.isEmpty(rs1.getString("PRIVILEGE")), form2.format(msgArgs2[6])); + assertTrue(!StringUtils.isEmpty(rs1.getString("IS_GRANTABLE")), form2.format(msgArgs2[7])); + } + } } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); @@ -489,50 +460,43 @@ public void testGetFunctions() throws SQLException { } /** - * Te * * @throws SQLException */ @Test public void testGetFunctionColumns() throws SQLException { - ResultSet rsFunctions = null; - ResultSet rs = null; try (Connection conn = DriverManager.getConnection(connectionString)) { DatabaseMetaData databaseMetaData = conn.getMetaData(); - rsFunctions = databaseMetaData.getFunctions(null, null, "%"); - - // Fetch one Function - MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); - Object[] msgArgs1 = {"function"}; - assertTrue(rsFunctions.next(), form1.format(msgArgs1)); - - rs = databaseMetaData.getFunctionColumns(null, null, rsFunctions.getString("FUNCTION_NAME"), "%"); - - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameNull")); - Object[][] msgArgs2 = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"COLUMN_NAME"}, - {"COLUMN_TYPE"}, {"DATA_TYPE"}, {"TYPE_NAME"}, {"NULLABLE"}, {"IS_NULLABLE"}}; - while (rs.next()) { - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_CAT")), form2.format(msgArgs2[0])); - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_SCHEM")), form2.format(msgArgs2[1])); - assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_NAME")), form2.format(msgArgs2[2])); - assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); - assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_TYPE")), form2.format(msgArgs2[4])); - assertTrue(!StringUtils.isEmpty(rs.getString("DATA_TYPE")), form2.format(msgArgs2[5])); - assertTrue(!StringUtils.isEmpty(rs.getString("TYPE_NAME")), form2.format(msgArgs2[6])); - assertTrue(!StringUtils.isEmpty(rs.getString("NULLABLE")), form2.format(msgArgs2[7])); // 12 - assertTrue(!StringUtils.isEmpty(rs.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 19 + try (ResultSet rsFunctions = databaseMetaData.getFunctions(null, null, "%")) { + + // Fetch one Function + MessageFormat form1 = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); + Object[] msgArgs1 = {"function"}; + assertTrue(rsFunctions.next(), form1.format(msgArgs1)); + + try (ResultSet rs = databaseMetaData.getFunctionColumns(null, null, + rsFunctions.getString("FUNCTION_NAME"), "%")) { + + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_nameNull")); + Object[][] msgArgs2 = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"COLUMN_NAME"}, + {"COLUMN_TYPE"}, {"DATA_TYPE"}, {"TYPE_NAME"}, {"NULLABLE"}, {"IS_NULLABLE"}}; + while (rs.next()) { + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_CAT")), form2.format(msgArgs2[0])); + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_SCHEM")), form2.format(msgArgs2[1])); + assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_NAME")), form2.format(msgArgs2[2])); + assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_NAME")), form2.format(msgArgs2[3])); + assertTrue(!StringUtils.isEmpty(rs.getString("COLUMN_TYPE")), form2.format(msgArgs2[4])); + assertTrue(!StringUtils.isEmpty(rs.getString("DATA_TYPE")), form2.format(msgArgs2[5])); + assertTrue(!StringUtils.isEmpty(rs.getString("TYPE_NAME")), form2.format(msgArgs2[6])); + assertTrue(!StringUtils.isEmpty(rs.getString("NULLABLE")), form2.format(msgArgs2[7])); // 12 + assertTrue(!StringUtils.isEmpty(rs.getString("IS_NULLABLE")), form2.format(msgArgs2[8])); // 19 + } + } } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != rsFunctions) { - rsFunctions.close(); - } - if (null != rs) { - rs.close(); - } } } } From 524143d5c65cbf15c8e5444ffb5037d7c6b3a8b5 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Tue, 4 Sep 2018 11:54:12 -0700 Subject: [PATCH 08/15] review updates --- .../jdbc/AlwaysEncrypted/AESetup.java | 61 +- .../CallableStatementTest.java | 99 ++- .../JDBCEncryptionDecryptionTest.java | 24 +- .../AlwaysEncrypted/PrecisionScaleTest.java | 16 +- .../util => jdbc}/ComparisonUtil.java | 5 +- .../microsoft/sqlserver/jdbc/JDBC43Test.java | 13 +- .../util => jdbc}/RandomData.java | 2 +- .../util => jdbc}/RandomUtil.java | 2 +- .../util/Util.java => jdbc/TestUtils.java} | 656 +++++++++++++----- .../jdbc/bulkCopy/BulkCopyAllTypes.java | 8 +- .../jdbc/bulkCopy/BulkCopyCSVTest.java | 6 +- .../bulkCopy/BulkCopyColumnMappingTest.java | 3 +- .../bulkCopy/BulkCopyResultSetCursorTest.java | 6 +- .../jdbc/bulkCopy/BulkCopyTestUtil.java | 2 +- .../ISQLServerBulkRecordIssuesTest.java | 10 +- .../CallableStatementTest.java | 18 +- .../jdbc/connection/ConnectionDriverTest.java | 2 +- .../jdbc/connection/DBMetadataTest.java | 2 +- .../jdbc/connection/DriverVersionTest.java | 4 +- .../jdbc/connection/PoolingTest.java | 2 +- .../RequestBoundaryMethodsTest.java | 36 +- .../jdbc/connection/TimeoutTest.java | 6 +- .../DatabaseMetaDataForeignKeyTest.java | 12 +- .../DatabaseMetaDataTest.java | 12 +- .../datatypes/BulkCopyWithSqlVariantTest.java | 28 +- .../jdbc/datatypes/DateAndTimeTypeTest.java | 6 +- .../SQLServerSpatialDatatypeTest.java | 12 +- .../datatypes/SQLVariantResultSetTest.java | 48 +- .../jdbc/datatypes/TVPWithSqlVariantTest.java | 12 +- .../jdbc/exception/ExceptionTest.java | 6 +- .../sqlserver/jdbc/fips/FipsEnvTest.java | 20 +- .../sqlserver/jdbc/fips/FipsTest.java | 6 +- .../ParameterMetaDataTest.java | 8 +- .../ParameterMetaDataWhiteSpaceTest.java | 6 +- .../BatchExecutionWithBulkCopyTest.java | 22 +- .../BatchExecutionWithNullTest.java | 6 +- .../preparedStatement/RegressionTest.java | 16 +- .../resultset/DataClassificationTest.java | 9 +- .../jdbc/resultset/ResultSetTest.java | 8 +- .../sqlserver/jdbc/tvp/TVPAllTypes.java | 12 +- .../sqlserver/jdbc/tvp/TVPIssuesTest.java | 22 +- .../jdbc/tvp/TVPResultSetCursorTest.java | 8 +- .../sqlserver/jdbc/unit/TestSavepoint.java | 2 +- .../sqlserver/jdbc/unit/UTF8SupportTest.java | 16 +- .../sqlserver/jdbc/unit/lobs/lobsTest.java | 20 +- .../statement/BatchExecuteWithErrorsTest.java | 10 +- .../unit/statement/BatchExecutionTest.java | 6 +- .../jdbc/unit/statement/BatchTriggerTest.java | 4 +- .../unit/statement/CallableMixedTest.java | 8 +- .../jdbc/unit/statement/LimitEscapeTest.java | 10 +- .../jdbc/unit/statement/MergeTest.java | 4 +- .../statement/NamedParamMultiPartTest.java | 6 +- .../jdbc/unit/statement/PQImpsTest.java | 26 +- .../jdbc/unit/statement/PoolableTest.java | 4 +- .../jdbc/unit/statement/RegressionTest.java | 12 +- .../jdbc/unit/statement/StatementTest.java | 48 +- .../sqlserver/testframework/AbstractTest.java | 5 +- .../testframework/DBInvalidUtil.java | 4 +- .../sqlserver/testframework/DBResultSet.java | 7 +- .../sqlserver/testframework/DBTable.java | 2 +- .../sqlserver/testframework/Utils.java | 332 --------- .../testframework/sqlType/SqlChar.java | 4 +- .../testframework/sqlType/SqlVarBinary.java | 4 +- 63 files changed, 883 insertions(+), 913 deletions(-) rename src/test/java/com/microsoft/sqlserver/{testframework/util => jdbc}/ComparisonUtil.java (97%) rename src/test/java/com/microsoft/sqlserver/{testframework/util => jdbc}/RandomData.java (99%) rename src/test/java/com/microsoft/sqlserver/{testframework/util => jdbc}/RandomUtil.java (94%) rename src/test/java/com/microsoft/sqlserver/{testframework/util/Util.java => jdbc/TestUtils.java} (52%) delete mode 100644 src/test/java/com/microsoft/sqlserver/testframework/Utils.java 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 276c55683..f3c63208b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -27,6 +27,7 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomData; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerConnection; @@ -34,11 +35,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatementColumnEncryptionSetting; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomData; -import com.microsoft.sqlserver.testframework.util.Util; import microsoft.sql.DateTimeOffset; @@ -97,7 +96,7 @@ public static void setUpConnection() throws TestAbortedException, Exception { dropCMK(stmt); } - keyPath = Utils.getCurrentClassPath() + jksName; + keyPath = TestUtils.getCurrentClassPath() + jksName; storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, secretstrJks.toCharArray()); stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.Enabled; @@ -124,7 +123,7 @@ public static void dropAll() throws SQLException { dropTables(stmt); dropCEK(stmt); dropCMK(stmt); - Util.close(null, stmt, con); + TestUtils.close(null, stmt, con); } /** @@ -136,7 +135,7 @@ public static void dropAll() throws SQLException { * @throws IOException */ private static void readFromFile(String inputFile, String lookupValue) throws IOException { - filePath = Utils.getCurrentClassPath(); + filePath = TestUtils.getCurrentClassPath(); try { File f = new File(filePath + inputFile); assumeTrue(f.exists(), TestResource.getResource("R_noKeyStore")); @@ -703,7 +702,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" + TestUtils.bytesToHexString(key, key.length) + ")" + ";"; stmt.execute(cekSql); } @@ -713,10 +712,10 @@ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storePro * @throws SQLException */ protected static void dropTables(SQLServerStatement statement) throws SQLException { - Utils.dropTableIfExists(numericTable, statement); - Utils.dropTableIfExists(charTable, statement); - Utils.dropTableIfExists(binaryTable, statement); - Utils.dropTableIfExists(dateTable, statement); + TestUtils.dropTableIfExists(numericTable, statement); + TestUtils.dropTableIfExists(charTable, statement); + TestUtils.dropTableIfExists(binaryTable, statement); + TestUtils.dropTableIfExists(dateTable, statement); } /** @@ -729,7 +728,7 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // binary20 @@ -791,7 +790,7 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // binary(20) @@ -853,7 +852,7 @@ protected static void populateBinarySetObjectWithJDBCType(LinkedList byt String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // binary(20) @@ -914,7 +913,7 @@ protected static void populateBinaryNullCase() throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // binary @@ -951,7 +950,7 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1017,7 +1016,7 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1079,7 +1078,7 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1140,7 +1139,7 @@ protected static void populateCharNullCase() throws SQLException { String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1193,7 +1192,7 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1239,7 +1238,7 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro protected static void populateDateScaleNormalCase(LinkedList dateValues) throws SQLException { String sql = "insert into " + scaleDateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // datetime2(2) @@ -1276,7 +1275,7 @@ protected static void populateDateSetObject(LinkedList dateValues, Strin String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1342,7 +1341,7 @@ protected void populateDateSetObjectNull() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1388,7 +1387,7 @@ protected static void populateDateNullCase() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1436,7 +1435,7 @@ protected static void populateNumeric(String[] values) throws SQLException { + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1544,7 +1543,7 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1652,7 +1651,7 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1759,7 +1758,7 @@ protected static void populateNumericSetObjectNull() throws SQLException { + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1859,7 +1858,7 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1958,7 +1957,7 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -2086,6 +2085,6 @@ private static void dropCMK(SQLServerStatement stmt) throws SQLException { * @throws TestAbortedException */ protected static void skipTestForJava7() throws TestAbortedException, SQLException { - assumeTrue(Util.supportJDBC42(con)); // With Java 7, skip tests for JDBCType. + assumeTrue(TestUtils.supportJDBC42(con)); // With Java 7, skip tests for JDBCType. } } 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 815e7486e..eeee0f717 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -22,13 +22,12 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomData; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomData; -import com.microsoft.sqlserver.testframework.util.Util; +import com.microsoft.sqlserver.jdbc.TestUtils; import microsoft.sql.DateTimeOffset; @@ -245,27 +244,27 @@ public void testOutputProcedure4() throws SQLException { } private static void dropTables() throws SQLException { - Utils.dropTableIfExists(table1, stmt); + TestUtils.dropTableIfExists(table1, stmt); - Utils.dropTableIfExists(table2, stmt); + TestUtils.dropTableIfExists(table2, stmt); - Utils.dropTableIfExists(table3, stmt); + TestUtils.dropTableIfExists(table3, stmt); - Utils.dropTableIfExists(table4, stmt); + TestUtils.dropTableIfExists(table4, stmt); - Utils.dropTableIfExists(charTable, stmt); + TestUtils.dropTableIfExists(charTable, stmt); - Utils.dropTableIfExists(numericTable, stmt); + TestUtils.dropTableIfExists(numericTable, stmt); - Utils.dropTableIfExists(binaryTable, stmt); + TestUtils.dropTableIfExists(binaryTable, stmt); - Utils.dropTableIfExists(dateTable, stmt); + TestUtils.dropTableIfExists(dateTable, stmt); - Utils.dropTableIfExists(table5, stmt); + TestUtils.dropTableIfExists(table5, stmt); - Utils.dropTableIfExists(table6, stmt); + TestUtils.dropTableIfExists(table6, stmt); - Utils.dropTableIfExists(scaleDateTable, stmt); + TestUtils.dropTableIfExists(scaleDateTable, stmt); } private static void createTables() throws SQLException { @@ -461,7 +460,7 @@ private static void createTables() throws SQLException { private static void populateTable4() throws SQLException { String sql = "insert into " + table4 + " values( " + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -478,7 +477,7 @@ private static void populateTable3() throws SQLException { + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -596,7 +595,7 @@ private void MultiInsertionSelection() throws SQLException { try { String sql = "{call " + multiStatementsProcedure + " (?,?,?,?,?,?)}"; - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { // char, varchar @@ -666,7 +665,7 @@ private void createInputProcedure() throws SQLException { private void testInputProcedure(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(values[3])); @@ -720,7 +719,7 @@ private void createInputProcedure2() throws SQLException { private void testInputProcedure2(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setString(1, charValues[1]); @@ -763,7 +762,7 @@ private void createOutputProcedure3() throws SQLException { private void testOutputProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -792,7 +791,7 @@ private void testOutputProcedure3RandomOrder(String sql) throws SQLException { private void testOutputProcedure3Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -812,7 +811,7 @@ private void testOutputProcedure3Inorder(String sql) throws SQLException { private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -847,7 +846,7 @@ private void createOutputProcedure2() throws SQLException { private void testOutputProcedure2RandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -899,7 +898,7 @@ private void testOutputProcedure2RandomOrder(String sql, String[] values) throws private void testOutputProcedure2Inorder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -951,7 +950,7 @@ private void testOutputProcedure2Inorder(String sql, String[] values) throws SQL private void testOutputProcedure2ReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1017,7 +1016,7 @@ private void createOutputProcedure() throws SQLException { private void testOutputProcedureRandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1065,7 +1064,7 @@ private void testOutputProcedureRandomOrder(String sql, String[] values) throws private void testOutputProcedureInorder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1106,7 +1105,7 @@ private void testOutputProcedureInorder(String sql, String[] values) throws SQLE private void testOutputProcedureReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1157,7 +1156,7 @@ private void createInOutProcedure() throws SQLException { private void testInOutProcedure(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(numericValues[3])); @@ -1186,7 +1185,7 @@ private void createMixedProcedure() throws SQLException { private void testMixedProcedure(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1226,7 +1225,7 @@ private void createMixedProcedure2() throws SQLException { private void testMixedProcedure2RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1260,7 +1259,7 @@ private void testMixedProcedure2RandomOrder(String sql) throws SQLException { private void testMixedProcedure2Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1294,7 +1293,7 @@ private void createMixedProcedure3() throws SQLException { private void testMixedProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); @@ -1328,7 +1327,7 @@ private void testMixedProcedure3RandomOrder(String sql) throws SQLException { private void testMixedProcedure3Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); @@ -1349,7 +1348,7 @@ private void testMixedProcedure3Inorder(String sql) throws SQLException { private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); @@ -1385,7 +1384,7 @@ private void createMixedProcedureNumericPrcisionScale() throws SQLException { private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DECIMAL, 18, 0); @@ -1415,7 +1414,7 @@ private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter("p1", java.sql.Types.DECIMAL, 18, 0); @@ -1461,7 +1460,7 @@ private void createOutputProcedureChar() throws SQLException { private void testOutputProcedureCharInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); @@ -1509,7 +1508,7 @@ private void testOutputProcedureCharInorder(String sql) throws SQLException { private void testOutputProcedureCharInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); @@ -1578,7 +1577,7 @@ private void createOutputProcedureNumeric() throws SQLException { private void testOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIT); callableStatement.registerOutParameter(2, java.sql.Types.TINYINT); @@ -1665,7 +1664,7 @@ private void testOutputProcedureNumericInorder(String sql) throws SQLException { private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIT); callableStatement.registerOutParameter(2, java.sql.Types.TINYINT); @@ -1960,7 +1959,7 @@ private void createOutputProcedureBinary() throws SQLException { private void testOutputProcedureBinaryInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BINARY, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARBINARY, 50, 0); @@ -2006,7 +2005,7 @@ private void testOutputProcedureBinaryInorder(String sql) throws SQLException { private void testOutputProcedureBinaryInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BINARY, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARBINARY, 50, 0); @@ -2045,7 +2044,7 @@ private void testOutputProcedureBinaryInorderObject(String sql) throws SQLExcept private void testOutputProcedureBinaryInorderString(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BINARY, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARBINARY, 50, 0); @@ -2177,7 +2176,7 @@ private static void populateDateNormalCase() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting); // date @@ -2249,7 +2248,7 @@ private void createOutputProcedureDate() throws SQLException { private void testOutputProcedureDateInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); @@ -2301,7 +2300,7 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { private void testOutputProcedureDateInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); @@ -2369,7 +2368,7 @@ private void createOutputProcedureBatch() throws SQLException { private void testOutputProcedureBatchInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -2426,7 +2425,7 @@ private void createMixedProcedureDateScale() throws SQLException { private void testMixedProcedureDateScaleInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter(2, java.sql.Types.TIMESTAMP, 2); @@ -2455,7 +2454,7 @@ private void testMixedProcedureDateScaleInorder(String sql) throws SQLException private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter("p1", java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter("p2", java.sql.Types.TIMESTAMP, 2); 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 5c0fe7d6b..0448f3fff 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java @@ -17,12 +17,12 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomData; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.util.RandomData; -import com.microsoft.sqlserver.testframework.util.Util; +import com.microsoft.sqlserver.jdbc.TestUtils; /** @@ -516,7 +516,7 @@ public void testNumericNormalization() throws SQLException { private void testChar(SQLServerStatement stmt, String[] values) throws SQLException { String sql = "select * from " + charTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); @@ -530,7 +530,7 @@ private void testChar(SQLServerStatement stmt, String[] values) throws SQLExcept private void testBinary(SQLServerStatement stmt, LinkedList values) throws SQLException { String sql = "select * from " + binaryTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); @@ -545,7 +545,7 @@ private void testBinary(SQLServerStatement stmt, LinkedList values) thro private void testDate(SQLServerStatement stmt, LinkedList values1) throws SQLException { String sql = "select * from " + dateTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); @@ -599,9 +599,9 @@ private void testGetObjectForTemporal(ResultSet rs, int numberOfColumns, Object expected = null; if (rs.getMetaData().getColumnTypeName(i).equalsIgnoreCase("smalldatetime")) { - expected = Util.roundSmallDateTimeValue(values.get(index)); + expected = TestUtils.roundSmallDateTimeValue(values.get(index)); } else if (rs.getMetaData().getColumnTypeName(i).equalsIgnoreCase("datetime")) { - expected = Util.roundDatetimeValue(values.get(index)); + expected = TestUtils.roundDatetimeValue(values.get(index)); } else { expected = values.get(index); } @@ -758,7 +758,7 @@ private void testGetStringForDate(ResultSet rs, int numberOfColumns, + TestResource.getResource("R_expectedValue") + values.get(index)); } else if (index == 4) // round value for datetime { - Object datetimeValue = "" + Util.roundDatetimeValue(values.get(index)); + Object datetimeValue = "" + TestUtils.roundDatetimeValue(values.get(index)); assertTrue( stringValue1.equalsIgnoreCase("" + datetimeValue) && stringValue2.equalsIgnoreCase("" + datetimeValue) @@ -768,7 +768,7 @@ private void testGetStringForDate(ResultSet rs, int numberOfColumns, + TestResource.getResource("R_expectedValue") + datetimeValue); } else if (index == 5) // round value for smalldatetime { - Object smalldatetimeValue = "" + Util.roundSmallDateTimeValue(values.get(index)); + Object smalldatetimeValue = "" + TestUtils.roundSmallDateTimeValue(values.get(index)); assertTrue( stringValue1.equalsIgnoreCase("" + smalldatetimeValue) && stringValue2.equalsIgnoreCase("" + smalldatetimeValue) @@ -896,14 +896,14 @@ private void testGetDate(ResultSet rs, int numberOfColumns, LinkedList v stringValue1 = "" + ((SQLServerResultSet) rs).getDateTime(i); stringValue2 = "" + ((SQLServerResultSet) rs).getDateTime(i + 1); stringValue3 = "" + ((SQLServerResultSet) rs).getDateTime(i + 2); - expected = "" + Util.roundDatetimeValue(values.get(4)); + expected = "" + TestUtils.roundDatetimeValue(values.get(4)); break; case 16: stringValue1 = "" + ((SQLServerResultSet) rs).getSmallDateTime(i); stringValue2 = "" + ((SQLServerResultSet) rs).getSmallDateTime(i + 1); stringValue3 = "" + ((SQLServerResultSet) rs).getSmallDateTime(i + 2); - expected = "" + Util.roundSmallDateTimeValue(values.get(5)); + expected = "" + TestUtils.roundSmallDateTimeValue(values.get(5)); break; default: @@ -926,7 +926,7 @@ private void testGetDate(ResultSet rs, int numberOfColumns, LinkedList v private void testNumeric(Statement stmt, String[] numericValues, boolean isNull) throws SQLException { String sql = "select * from " + numericTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (SQLServerResultSet rs = (stmt == null) ? (SQLServerResultSet) pstmt.executeQuery() : (SQLServerResultSet) stmt.executeQuery(sql)) { 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 36ccd8848..431b0fce5 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -23,7 +23,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.util.Util; +import com.microsoft.sqlserver.jdbc.TestUtils; /** @@ -339,7 +339,7 @@ private void populateDateNormalCase(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // datetime2(5) @@ -381,7 +381,7 @@ private void populateDateNormalCaseNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // datetime2(5) @@ -421,7 +421,7 @@ private void populateDateNormalCaseNull(int scale) throws SQLException { private void populateNumericNormalCase(String[] numeric, int precision, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // float(30) @@ -446,7 +446,7 @@ private void populateNumericNormalCase(String[] numeric, int precision, int scal private void populateNumericSetObject(String[] numeric, int precision, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // float(30) @@ -472,7 +472,7 @@ private void populateNumericSetObject(String[] numeric, int precision, int scale private void populateNumericSetObjectNull(int precision, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // float(30) @@ -499,7 +499,7 @@ private void populateDateSetObject(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // datetime2(5) @@ -542,7 +542,7 @@ private void populateDateSetObjectNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // datetime2(5) diff --git a/src/test/java/com/microsoft/sqlserver/testframework/util/ComparisonUtil.java b/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java similarity index 97% rename from src/test/java/com/microsoft/sqlserver/testframework/util/ComparisonUtil.java rename to src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java index 30a7e9d93..4f0f266e7 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/util/ComparisonUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java @@ -3,7 +3,7 @@ * available under the terms of the MIT License. See the LICENSE file in the project root for more information. */ -package com.microsoft.sqlserver.testframework.util; +package com.microsoft.sqlserver.jdbc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -22,7 +22,6 @@ import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.Utils; public class ComparisonUtil { @@ -156,7 +155,7 @@ public static void compareExpectedAndActual(int dataType, Object expectedValue, case java.sql.Types.BINARY: case java.sql.Types.VARBINARY: - assertTrue(Utils.parseByte((byte[]) expectedValue, (byte[]) actualValue), + assertTrue(TestUtils.parseByte((byte[]) expectedValue, (byte[]) actualValue), "Unexpected bianry/varbinary value "); break; diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java b/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java index 9979ed6c7..b688db202 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java @@ -25,8 +25,7 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; -import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.util.Util;; +import com.microsoft.sqlserver.testframework.AbstractTest;; /** @@ -48,7 +47,7 @@ public class JDBC43Test extends AbstractTest { */ @Test public void connectionBuilderTest() throws TestAbortedException, SQLException { - assumeTrue(Util.supportJDBC43(connection)); + assumeTrue(TestUtils.supportJDBC43(connection)); SQLServerDataSource ds = new SQLServerDataSource(); try { superShardingKey = ds.createShardingKeyBuilder().subkey("EASTERN_REGION", JDBCType.VARCHAR).build(); @@ -80,7 +79,7 @@ public void connectionBuilderTest() throws TestAbortedException, SQLException { */ @Test public void xaConnectionBuilderTest() throws TestAbortedException, SQLException { - assumeTrue(Util.supportJDBC43(connection)); + assumeTrue(TestUtils.supportJDBC43(connection)); SQLServerXADataSource ds = new SQLServerXADataSource(); try { superShardingKey = ds.createShardingKeyBuilder().subkey("EASTERN_REGION", JDBCType.VARCHAR).build(); @@ -111,7 +110,7 @@ public void xaConnectionBuilderTest() throws TestAbortedException, SQLException */ @Test public void connectionPoolDataSourceTest() throws TestAbortedException, SQLException { - assumeTrue(Util.supportJDBC43(connection)); + assumeTrue(TestUtils.supportJDBC43(connection)); ConnectionPoolDataSource ds = new SQLServerConnectionPoolDataSource(); try { superShardingKey = ds.createShardingKeyBuilder().subkey("EASTERN_REGION", JDBCType.VARCHAR).build(); @@ -141,7 +140,7 @@ public void connectionPoolDataSourceTest() throws TestAbortedException, SQLExcep */ @Test public void setShardingKeyIfValidTest() throws TestAbortedException, SQLException { - assumeTrue(Util.supportJDBC43(connection)); + assumeTrue(TestUtils.supportJDBC43(connection)); SQLServerConnection connection43 = (SQLServerConnection43) DriverManager.getConnection(connectionString); try { connection43.setShardingKeyIfValid(shardingKey, 10); @@ -165,7 +164,7 @@ public void setShardingKeyIfValidTest() throws TestAbortedException, SQLExceptio */ @Test public void setShardingKeyTest() throws TestAbortedException, SQLException { - assumeTrue(Util.supportJDBC43(connection)); + assumeTrue(TestUtils.supportJDBC43(connection)); SQLServerConnection connection43 = (SQLServerConnection43) DriverManager.getConnection(connectionString); try { connection43.setShardingKey(shardingKey); diff --git a/src/test/java/com/microsoft/sqlserver/testframework/util/RandomData.java b/src/test/java/com/microsoft/sqlserver/jdbc/RandomData.java similarity index 99% rename from src/test/java/com/microsoft/sqlserver/testframework/util/RandomData.java rename to src/test/java/com/microsoft/sqlserver/jdbc/RandomData.java index 7d367f262..2e2b2e8a0 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/util/RandomData.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/RandomData.java @@ -3,7 +3,7 @@ * available under the terms of the MIT License. See the LICENSE file in the project root for more information. */ -package com.microsoft.sqlserver.testframework.util; +package com.microsoft.sqlserver.jdbc; import java.math.BigDecimal; import java.math.BigInteger; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/util/RandomUtil.java b/src/test/java/com/microsoft/sqlserver/jdbc/RandomUtil.java similarity index 94% rename from src/test/java/com/microsoft/sqlserver/testframework/util/RandomUtil.java rename to src/test/java/com/microsoft/sqlserver/jdbc/RandomUtil.java index f3b00ffbc..4d1c71ed6 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/util/RandomUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/RandomUtil.java @@ -3,7 +3,7 @@ * available under the terms of the MIT License. See the LICENSE file in the project root for more information. */ -package com.microsoft.sqlserver.testframework.util; +package com.microsoft.sqlserver.jdbc; import java.util.UUID; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/util/Util.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java similarity index 52% rename from src/test/java/com/microsoft/sqlserver/testframework/util/Util.java rename to src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java index 6b66613a3..c1e39eedb 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/util/Util.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java @@ -3,8 +3,14 @@ * available under the terms of the MIT License. See the LICENSE file in the project root for more information. */ -package com.microsoft.sqlserver.testframework.util; +package com.microsoft.sqlserver.jdbc; +import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.CharArrayReader; +import java.net.URI; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; @@ -12,41 +18,418 @@ import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; +import java.util.logging.Level; +import java.util.logging.Logger; -import com.microsoft.sqlserver.jdbc.SQLServerConnection; -import com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData; -import com.microsoft.sqlserver.jdbc.SQLServerStatementColumnEncryptionSetting; +import com.microsoft.sqlserver.testframework.sqlType.SqlBigInt; +import com.microsoft.sqlserver.testframework.sqlType.SqlBinary; +import com.microsoft.sqlserver.testframework.sqlType.SqlBit; +import com.microsoft.sqlserver.testframework.sqlType.SqlChar; +import com.microsoft.sqlserver.testframework.sqlType.SqlDate; +import com.microsoft.sqlserver.testframework.sqlType.SqlDateTime; +import com.microsoft.sqlserver.testframework.sqlType.SqlDateTime2; +import com.microsoft.sqlserver.testframework.sqlType.SqlDateTimeOffset; +import com.microsoft.sqlserver.testframework.sqlType.SqlDecimal; +import com.microsoft.sqlserver.testframework.sqlType.SqlFloat; +import com.microsoft.sqlserver.testframework.sqlType.SqlInt; +import com.microsoft.sqlserver.testframework.sqlType.SqlMoney; +import com.microsoft.sqlserver.testframework.sqlType.SqlNChar; +import com.microsoft.sqlserver.testframework.sqlType.SqlNVarChar; +import com.microsoft.sqlserver.testframework.sqlType.SqlNVarCharMax; +import com.microsoft.sqlserver.testframework.sqlType.SqlNumeric; +import com.microsoft.sqlserver.testframework.sqlType.SqlReal; +import com.microsoft.sqlserver.testframework.sqlType.SqlSmallDateTime; +import com.microsoft.sqlserver.testframework.sqlType.SqlSmallInt; +import com.microsoft.sqlserver.testframework.sqlType.SqlSmallMoney; +import com.microsoft.sqlserver.testframework.sqlType.SqlTime; +import com.microsoft.sqlserver.testframework.sqlType.SqlTinyInt; +import com.microsoft.sqlserver.testframework.sqlType.SqlType; +import com.microsoft.sqlserver.testframework.sqlType.SqlVarBinary; +import com.microsoft.sqlserver.testframework.sqlType.SqlVarBinaryMax; +import com.microsoft.sqlserver.testframework.sqlType.SqlVarChar; +import com.microsoft.sqlserver.testframework.sqlType.SqlVarCharMax; /** - * Utility class for testing + * Generic Utility class which we can access by test classes. + * + * @since 6.1.2 */ -public class Util { +public class TestUtils { + public static final Logger log = Logger.getLogger("TestUtils"); + + // 'SQL' represents SQL Server, while 'SQLAzure' represents SQL Azure. + public static final String SERVER_TYPE_SQL_SERVER = "SQL"; + public static final String SERVER_TYPE_SQL_AZURE = "SQLAzure"; + // private static SqlType types = null; + private static ArrayList types = null; /** - * Utility method for generating a prepared statement + * Returns serverType + * + * @return + */ + public static String getServerType() { + String serverType = null; + + String serverTypeProperty = getConfiguredProperty("server.type"); + if (null == serverTypeProperty) { + // default to SQL Server + serverType = SERVER_TYPE_SQL_SERVER; + } else if (serverTypeProperty.equalsIgnoreCase(SERVER_TYPE_SQL_AZURE)) { + serverType = SERVER_TYPE_SQL_AZURE; + } else if (serverTypeProperty.equalsIgnoreCase(SERVER_TYPE_SQL_SERVER)) { + serverType = SERVER_TYPE_SQL_SERVER; + } else { + if (log.isLoggable(Level.FINE)) { + log.fine("Server.type '" + serverTypeProperty + "' is not supported yet. Default to SQL Server"); + } + serverType = SERVER_TYPE_SQL_SERVER; + } + return serverType; + } + + /** + * Read variable from property files if found null try to read from env. + * + * @param key + * @return Value + */ + public static String getConfiguredProperty(String key) { + String value = System.getProperty(key); + + if (value == null) { + value = System.getenv(key); + } + + return value; + } + + /** + * Convenient method for {@link #getConfiguredProperty(String)} + * + * @param key + * @return Value + */ + public static String getConfiguredProperty(String key, String defaultValue) { + String value = getConfiguredProperty(key); + + if (value == null) { + value = defaultValue; + } + + return value; + } + + /** + * + * @param javatype + * @return + */ + public static SqlType find(Class javatype) { + if (null != types) { + types(); + for (SqlType type : types) { + if (type.getType() == javatype) + return type; + } + } + return null; + } + + /** + * + * @param name + * @return + */ + public static SqlType find(String name) { + if (null == types) + types(); + if (null != types) { + for (SqlType type : types) { + if (type.getName().equalsIgnoreCase(name)) + return type; + } + } + return null; + } + + /** + * + * @return + */ + public static ArrayList types() { + if (null == types) { + types = new ArrayList<>(); + + types.add(new SqlInt()); + types.add(new SqlSmallInt()); + types.add(new SqlTinyInt()); + types.add(new SqlBit()); + types.add(new SqlDateTime()); + types.add(new SqlSmallDateTime()); + types.add(new SqlDecimal()); + types.add(new SqlNumeric()); + types.add(new SqlReal()); + types.add(new SqlFloat()); + types.add(new SqlMoney()); + types.add(new SqlSmallMoney()); + types.add(new SqlVarChar()); + types.add(new SqlChar()); + // types.add(new SqlText()); + types.add(new SqlBinary()); + types.add(new SqlVarBinary()); + // types.add(new SqlImage()); + // types.add(new SqlTimestamp()); + + types.add(new SqlNVarChar()); + types.add(new SqlNChar()); + // types.add(new SqlNText()); + // types.add(new SqlGuid()); + + types.add(new SqlBigInt()); + // types.add(new SqlVariant(this)); + + // 9.0 types + types.add(new SqlVarCharMax()); + types.add(new SqlNVarCharMax()); + types.add(new SqlVarBinaryMax()); + // types.add(new SqlXml()); + + // 10.0 types + types.add(new SqlDate()); + types.add(new SqlDateTime2()); + types.add(new SqlTime()); + types.add(new SqlDateTimeOffset()); + } + return types; + } + + /** + * Wrapper Class for BinaryStream + * + */ + public static class DBBinaryStream extends ByteArrayInputStream { + byte[] data; + + // Constructor + public DBBinaryStream(byte[] value) { + super(value); + data = value; + } + + } + + /** + * Wrapper for CharacterStream + * + */ + public static class DBCharacterStream extends CharArrayReader { + String localValue; + + /** + * Constructor + * + * @param value + */ + public DBCharacterStream(String value) { + super(value.toCharArray()); + localValue = value; + } + + } + + /** + * Wrapper for NCharacterStream + */ + class DBNCharacterStream extends DBCharacterStream { + // Constructor + public DBNCharacterStream(String value) { + super(value); + } + } + + /** + * + * @return location of resource file + */ + public static String getCurrentClassPath() { + try { + String className = new Object() {}.getClass().getEnclosingClass().getName(); + String location = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath() + + "/"; + URI uri = new URI(location.toString()); + return uri.getPath(); + } catch (Exception e) { + fail("Failed to get CSV file path. " + e.getMessage()); + } + return null; + } + + /** + * mimic "DROP TABLE IF EXISTS ..." for older versions of SQL Server + */ + public static void dropTableIfExists(String tableName, java.sql.Statement stmt) throws SQLException { + dropObjectIfExists(tableName, "IsTable", stmt); + } + + /** + * mimic "DROP PROCEDURE IF EXISTS ..." for older versions of SQL Server + */ + public static void dropProcedureIfExists(String procName, java.sql.Statement stmt) throws SQLException { + dropObjectIfExists(procName, "IsProcedure", stmt); + } + + public static void dropDatabaseIfExists(String databaseName, java.sql.Statement stmt) throws SQLException { + stmt.executeUpdate("USE MASTER; IF EXISTS(SELECT * from sys.databases WHERE name='" + databaseName + + "') DROP DATABASE [" + databaseName + "]"); + } + + /** + * actually perform the "DROP TABLE / PROCEDURE" + */ + private static void dropObjectIfExists(String objectName, String objectProperty, + java.sql.Statement stmt) throws SQLException { + StringBuilder sb = new StringBuilder(); + if (!objectName.startsWith("[")) { + sb.append("["); + } + sb.append(objectName); + if (!objectName.endsWith("]")) { + sb.append("]"); + } + String bracketedObjectName = sb.toString(); + String sql = String.format("IF EXISTS " + "( " + "SELECT * from sys.objects " + + "WHERE object_id = OBJECT_ID(N'%s') AND OBJECTPROPERTY(object_id, N'%s') = 1 " + ") " + "DROP %s %s ", + bracketedObjectName, objectProperty, "IsProcedure".equals(objectProperty) ? "PROCEDURE" : "TABLE", + bracketedObjectName); + stmt.executeUpdate(sql); + } + + public static boolean parseByte(byte[] expectedData, byte[] retrieved) { + assertTrue(Arrays.equals(expectedData, Arrays.copyOf(retrieved, expectedData.length)), + " unexpected BINARY value, expected"); + for (int i = expectedData.length; i < retrieved.length; i++) { + assertTrue(0 == retrieved[i], "unexpected data BINARY"); + } + return true; + } + + public static boolean isJDBC43OrGreater(Connection connection) throws SQLException { + return getJDBCVersion(connection) >= 4.3F; + } + + public static float getJDBCVersion(Connection connection) throws SQLException { + return Float.valueOf( + connection.getMetaData().getJDBCMajorVersion() + "." + connection.getMetaData().getJDBCMinorVersion()); + } + + public static boolean serverSupportsUTF8(Connection connection) throws SQLException { + try (Statement stmt = connection.createStatement(); ResultSet rs = stmt + .executeQuery("SELECT name FROM sys.fn_helpcollations() WHERE name LIKE '%UTF8%'");) { + return rs.isBeforeFirst(); + } + } + + /** + * + * @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 SQLException + */ + static byte CharToHex(char value) throws SQLException { + 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; + } + + /** + * Utility function for safely closing open resultset/statement/connection + * + * @param ResultSet + * @param Statement + * @param Connection + */ + public static void close(ResultSet rs, Statement stmt, Connection con) { + if (rs != null) { + try { + rs.close(); + + } catch (SQLException e) { + System.out.println("The result set cannot be closed."); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + System.out.println("The statement cannot be closed."); + } + } + if (con != null) { + try { + con.close(); + } catch (SQLException e) { + System.out.println("The data source connection cannot be closed."); + } + } + } + + /** + * Utility method for a callable statement * * @param connection * connection object - * @param sql - * SQL string * @param stmtColEncSetting * SQLServerStatementColumnEncryptionSetting object + * @param sql * @return */ - public static PreparedStatement getPreparedStmt(Connection connection, String sql, + public static CallableStatement getCallableStmt(Connection connection, String sql, SQLServerStatementColumnEncryptionSetting stmtColEncSetting) throws SQLException { if (null == stmtColEncSetting) { - return ((SQLServerConnection) connection).prepareStatement(sql); + return ((SQLServerConnection) connection).prepareCall(sql); } else { - return ((SQLServerConnection) connection).prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, + return ((SQLServerConnection) connection).prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, connection.getHoldability(), stmtColEncSetting); } } /** - * Utility method for a statement + * Utility method for generating a prepared statement * * @param connection * connection object @@ -56,13 +439,12 @@ public static PreparedStatement getPreparedStmt(Connection connection, String sq * SQLServerStatementColumnEncryptionSetting object * @return */ - public static Statement getStatement(Connection connection, + public static PreparedStatement getPreparedStmt(Connection connection, String sql, SQLServerStatementColumnEncryptionSetting stmtColEncSetting) throws SQLException { - // default getStatement assumes resultSet is type_forward_only and concur_read_only if (null == stmtColEncSetting) { - return ((SQLServerConnection) connection).createStatement(); + return ((SQLServerConnection) connection).prepareStatement(sql); } else { - return ((SQLServerConnection) connection).createStatement(ResultSet.TYPE_FORWARD_ONLY, + return ((SQLServerConnection) connection).prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, connection.getHoldability(), stmtColEncSetting); } } @@ -99,90 +481,66 @@ public static Statement getScrollableStatement(Connection connection, * * @param connection * connection object + * @param sql + * SQL string * @param stmtColEncSetting * SQLServerStatementColumnEncryptionSetting object - * @param rsScrollSensitivity - * @param rsConcurrence * @return */ public static Statement getStatement(Connection connection, - SQLServerStatementColumnEncryptionSetting stmtColEncSetting, int rsScrollSensitivity, - int rsConcurrence) throws SQLException { - // overloaded getStatement allows setting resultSet type + SQLServerStatementColumnEncryptionSetting stmtColEncSetting) throws SQLException { + // default getStatement assumes resultSet is type_forward_only and concur_read_only if (null == stmtColEncSetting) { - return ((SQLServerConnection) connection).createStatement(rsScrollSensitivity, rsConcurrence, - connection.getHoldability()); + return ((SQLServerConnection) connection).createStatement(); } else { - return ((SQLServerConnection) connection).createStatement(rsScrollSensitivity, rsConcurrence, - connection.getHoldability(), stmtColEncSetting); + return ((SQLServerConnection) connection).createStatement(ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, connection.getHoldability(), stmtColEncSetting); } } /** - * Utility method for a callable statement + * Utility method for a statement * * @param connection * connection object * @param stmtColEncSetting * SQLServerStatementColumnEncryptionSetting object - * @param sql + * @param rsScrollSensitivity + * @param rsConcurrence * @return */ - public static CallableStatement getCallableStmt(Connection connection, String sql, - SQLServerStatementColumnEncryptionSetting stmtColEncSetting) throws SQLException { + public static Statement getStatement(Connection connection, + SQLServerStatementColumnEncryptionSetting stmtColEncSetting, int rsScrollSensitivity, + int rsConcurrence) throws SQLException { + // overloaded getStatement allows setting resultSet type if (null == stmtColEncSetting) { - return ((SQLServerConnection) connection).prepareCall(sql); + return ((SQLServerConnection) connection).createStatement(rsScrollSensitivity, rsConcurrence, + connection.getHoldability()); } else { - return ((SQLServerConnection) connection).prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY, connection.getHoldability(), stmtColEncSetting); + return ((SQLServerConnection) connection).createStatement(rsScrollSensitivity, rsConcurrence, + connection.getHoldability(), stmtColEncSetting); } } /** - * Utility method for a datetime value + * Converts a string to an array of bytes * - * @param value + * @param hexV + * a hexized string representation of bytes * @return + * @throws SQLException */ - public static Object roundSmallDateTimeValue(Object value) { - if (value == null) { - return null; - } - - Calendar cal; - java.sql.Timestamp ts = null; - int nanos = -1; - - if (value instanceof Calendar) { - cal = (Calendar) value; - } else { - ts = (java.sql.Timestamp) value; - cal = Calendar.getInstance(); - cal.setTimeInMillis(ts.getTime()); - nanos = ts.getNanos(); - } - - // round to the nearest minute - double seconds = cal.get(Calendar.SECOND) - + (nanos == -1 ? ((double) cal.get(Calendar.MILLISECOND) / 1000) : ((double) nanos / 1000000000)); - if (seconds > 29.998) { - cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 1); + public static byte[] hexStringToByte(String hexV) throws SQLException { + 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); } - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - nanos = 0; - - // required to force computation - cal.getTimeInMillis(); - - // return appropriate value - if (value instanceof Calendar) { - return cal; - } else { - ts.setTime(cal.getTimeInMillis()); - ts.setNanos(nanos); - return ts; + 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; } /** @@ -203,7 +561,7 @@ public static Object roundDatetimeValue(Object value) { case 1: ts.setNanos((millis - 1) * 1000000); break; - + // 2, 3, 4 -> 3 case 2: ts.setNanos((millis + 1) * 1000000); @@ -211,7 +569,7 @@ public static Object roundDatetimeValue(Object value) { case 4: ts.setNanos((millis - 1) * 1000000); break; - + // 5, 6, 7, 8 -> 7 case 5: ts.setNanos((millis + 2) * 1000000); @@ -222,13 +580,13 @@ public static Object roundDatetimeValue(Object value) { case 8: ts.setNanos((millis - 1) * 1000000); break; - + // 9 -> 0 with overflow case 9: ts.setNanos(0); ts.setTime(ts.getTime() + millis + 1); break; - + // default, i.e. 0, 3, 7 -> 0, 3, 7 // don't change the millis but make sure that any // sub-millisecond digits are zeroed out @@ -244,57 +602,50 @@ public static Object roundDatetimeValue(Object value) { } /** - * Utility function for safely closing open resultset/statement/connection + * Utility method for a datetime value * - * @param ResultSet - * @param Statement - * @param Connection + * @param value + * @return */ - public static void close(ResultSet rs, Statement stmt, Connection con) { - if (rs != null) { - try { - rs.close(); - - } catch (SQLException e) { - System.out.println("The result set cannot be closed."); - } + public static Object roundSmallDateTimeValue(Object value) { + if (value == null) { + return null; } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - System.out.println("The statement cannot be closed."); - } + + Calendar cal; + java.sql.Timestamp ts = null; + int nanos = -1; + + if (value instanceof Calendar) { + cal = (Calendar) value; + } else { + ts = (java.sql.Timestamp) value; + cal = Calendar.getInstance(); + cal.setTimeInMillis(ts.getTime()); + nanos = ts.getNanos(); } - if (con != null) { - try { - con.close(); - } catch (SQLException e) { - System.out.println("The data source connection cannot be closed."); - } + + // round to the nearest minute + double seconds = cal.get(Calendar.SECOND) + + (nanos == -1 ? ((double) cal.get(Calendar.MILLISECOND) / 1000) : ((double) nanos / 1000000000)); + if (seconds > 29.998) { + cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 1); + } + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + nanos = 0; + + // required to force computation + cal.getTimeInMillis(); + + // return appropriate value + if (value instanceof Calendar) { + return cal; + } else { + ts.setTime(cal.getTimeInMillis()); + ts.setNanos(nanos); + return ts; } - } - - /** - * Utility function for checking if the system supports JDBC 4.2 - * - * @param con - * @return - */ - public static boolean supportJDBC42(Connection con) throws SQLException { - SQLServerDatabaseMetaData meta = (SQLServerDatabaseMetaData) con.getMetaData(); - return (meta.getJDBCMajorVersion() >= 4 && meta.getJDBCMinorVersion() >= 2); - } - - /** - * Utility function for checking if the system supports JDBC 4.3 - * - * @param con - * @return - */ - public static boolean supportJDBC43(Connection con) throws SQLException { - SQLServerDatabaseMetaData meta = (SQLServerDatabaseMetaData) con.getMetaData(); - return (meta.getJDBCMajorVersion() >= 4 && meta.getJDBCMinorVersion() >= 3); } /** @@ -316,65 +667,24 @@ public static boolean serverSupportsDataClassification(Statement stmt) { } /** + * Utility function for checking if the system supports JDBC 4.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 + * @param con * @return - * @throws SQLException */ - static byte CharToHex(char value) throws SQLException { - 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; + public static boolean supportJDBC42(Connection con) throws SQLException { + SQLServerDatabaseMetaData meta = (SQLServerDatabaseMetaData) con.getMetaData(); + return (meta.getJDBCMajorVersion() >= 4 && meta.getJDBCMinorVersion() >= 2); } /** - * Converts a string to an array of bytes + * Utility function for checking if the system supports JDBC 4.3 * - * @param hexV - * a hexized string representation of bytes + * @param con * @return - * @throws SQLException */ - public static byte[] hexStringToByte(String hexV) throws SQLException { - 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; + public static boolean supportJDBC43(Connection con) throws SQLException { + SQLServerDatabaseMetaData meta = (SQLServerDatabaseMetaData) con.getMetaData(); + return (meta.getJDBCMajorVersion() >= 4 && meta.getJDBCMinorVersion() >= 3); } } 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 93d12eadd..ea9e2d8f7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java @@ -14,13 +14,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.ComparisonUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; 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; @RunWith(JUnitPlatform.class) @@ -84,8 +84,8 @@ private void setupVariation() throws SQLException { private void terminateVariation() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); - Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + TestUtils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); + TestUtils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); } } } 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 d55e5d607..47a5209da 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java @@ -24,17 +24,17 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.ComparisonUtil; import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; import com.microsoft.sqlserver.jdbc.SQLServerBulkCSVFileRecord; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; 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.sqlType.SqlType; -import com.microsoft.sqlserver.testframework.util.ComparisonUtil; /** @@ -66,7 +66,7 @@ public class BulkCopyCSVTest extends AbstractTest { public static void setUpConnection() { con = new DBConnection(connectionString); stmt = con.createStatement(); - filePath = Utils.getCurrentClassPath(); + filePath = TestUtils.getCurrentClassPath(); } /** 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 a76f87095..268867494 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -19,14 +19,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.ComparisonUtil; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.DBConnection; 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.sqlType.SqlType; -import com.microsoft.sqlserver.testframework.util.ComparisonUtil; /** 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 2504fa0a4..4d9b7f3e0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -24,8 +24,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -202,8 +202,8 @@ private static void populateSourceTable() throws SQLException { } private static void dropTables(Statement stmt) throws SQLException { - Utils.dropTableIfExists(srcTable, stmt); - Utils.dropTableIfExists(desTable, stmt); + TestUtils.dropTableIfExists(srcTable, stmt); + TestUtils.dropTableIfExists(desTable, stmt); } private static void createTables(Statement stmt) throws SQLException { 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 c06b306b2..34b1bee80 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java @@ -11,6 +11,7 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; +import com.microsoft.sqlserver.jdbc.ComparisonUtil; import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.TestResource; @@ -19,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.util.ComparisonUtil; /** 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 e0325b319..2b769daf0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java @@ -34,8 +34,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -220,8 +220,8 @@ public void testSendValidValueforBinaryColumnAsString() throws Exception { public static void setupHere() throws SQLException, SecurityException, IOException { con = (SQLServerConnection) DriverManager.getConnection(connectionString); stmt = con.createStatement(); - Utils.dropTableIfExists(destTable, stmt); - Utils.dropTableIfExists(srcTable, stmt); + TestUtils.dropTableIfExists(destTable, stmt); + TestUtils.dropTableIfExists(srcTable, stmt); } /** @@ -231,8 +231,8 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterEach public void afterEachTests() throws SQLException { - Utils.dropTableIfExists(destTable, stmt); - Utils.dropTableIfExists(srcTable, stmt); + TestUtils.dropTableIfExists(destTable, stmt); + TestUtils.dropTableIfExists(srcTable, stmt); } @AfterAll 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 ad7c9ae19..a3345a7ff 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -22,8 +22,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -49,10 +49,10 @@ public static void setupTest() throws SQLException { connection = DriverManager.getConnection(connectionString); stmt = connection.createStatement(); - Utils.dropTableIfExists(tableNameGUID, stmt); - Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); - Utils.dropProcedureIfExists(setNullProcedureName, stmt); - Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); + TestUtils.dropTableIfExists(tableNameGUID, stmt); + TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); + TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); + TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); createGUIDTable(stmt); createGUIDStoredProcedure(stmt); @@ -172,10 +172,10 @@ public void inputParamsTest() throws SQLException { */ @AfterAll public static void cleanup() throws SQLException { - Utils.dropTableIfExists(tableNameGUID, stmt); - Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); - Utils.dropProcedureIfExists(setNullProcedureName, stmt); - Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); + TestUtils.dropTableIfExists(tableNameGUID, stmt); + TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); + TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); + TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); if (null != stmt) { stmt.close(); 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 61c5cdfcc..91d6d3652 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -34,6 +34,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.ISQLServerConnection; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; @@ -42,7 +43,6 @@ import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.util.RandomUtil; @RunWith(JUnitPlatform.class) 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 54dba8705..94e512325 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java @@ -14,10 +14,10 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.util.RandomUtil; @RunWith(JUnitPlatform.class) 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 bf622a26b..b315a2778 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DriverVersionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DriverVersionTest.java @@ -14,8 +14,8 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.util.Util; /** @@ -43,7 +43,7 @@ public class DriverVersionTest extends AbstractTest { public void testConnectionDriver() throws SQLException { // the original way to create version byte array String interfaceLibVersion = generateInterfaceLibVersion(); - byte originalVersionBytes[] = Util.hexStringToByte(interfaceLibVersion); + byte originalVersionBytes[] = TestUtils.hexStringToByte(interfaceLibVersion); String originalBytes = Arrays.toString(originalVersionBytes); 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 879bb7f1a..b7b098a1b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -28,12 +28,12 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.ISQLServerConnection; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerXADataSource; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.util.RandomUtil; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java index a12588dbd..8f9c76442 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -27,12 +27,12 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.PrepUtil; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -75,7 +75,7 @@ public void testModifiableConnectionProperties() throws SQLException { boolean useBulkCopyForBatchInsert2 = false; try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { - if (Utils.isJDBC43OrGreater(con)) { + if (TestUtils.isJDBC43OrGreater(con)) { // Second database stmt.executeUpdate("CREATE DATABASE [" + sCatalog2 + "]"); @@ -135,7 +135,7 @@ public void testModifiableConnectionProperties() throws SQLException { } } finally { try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { - Utils.dropDatabaseIfExists(sCatalog2, stmt); + TestUtils.dropDatabaseIfExists(sCatalog2, stmt); } } } @@ -148,7 +148,7 @@ public void testModifiableConnectionProperties() throws SQLException { @Test public void testWarnings() throws SQLException { try (SQLServerConnection con = connect()) { - if (Utils.isJDBC43OrGreater(con)) { + if (TestUtils.isJDBC43OrGreater(con)) { con.beginRequest(); generateWarning(con); assertNotNull(con.getWarnings()); @@ -176,13 +176,12 @@ public void testWarnings() throws SQLException { */ @Test public void testOpenTransactions() throws SQLException { - ResultSet rs = null; String tableName = null; try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { - if (Utils.isJDBC43OrGreater(con)) { + if (TestUtils.isJDBC43OrGreater(con)) { tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundaryTable")); - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("CREATE TABLE " + tableName + " (col int)"); con.beginRequest(); con.setAutoCommit(false); @@ -191,19 +190,16 @@ public void testOpenTransactions() throws SQLException { con.endRequest(); con.commit(); - rs = con.createStatement().executeQuery("SELECT * from " + tableName); - assertTrue(!rs.isBeforeFirst(), "Should not have returned a result set."); + try (ResultSet rs = con.createStatement().executeQuery("SELECT * from " + tableName)) { + assertTrue(!rs.isBeforeFirst(), "Should not have returned a result set."); + } } } catch (Exception e) { e.printStackTrace(); - } finally { - if (null != rs) { - rs.close(); - } - + } finally { if (null != tableName) { try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } } } @@ -226,7 +222,7 @@ public void testStatements() throws SQLException { String tableName = null; try (SQLServerConnection con = connect();) { - if (Utils.isJDBC43OrGreater(con)) { + if (TestUtils.isJDBC43OrGreater(con)) { stmt1 = con.createStatement(); con.beginRequest(); stmt = con.createStatement(); @@ -246,7 +242,7 @@ public void testStatements() throws SQLException { con.beginRequest(); stmt = con.createStatement(); tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundary")); - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("CREATE TABLE " + tableName + " (col int)"); ps = con.prepareStatement("INSERT INTO " + tableName + " values (?)"); ps.setInt(1, 2); @@ -282,7 +278,7 @@ public void testStatements() throws SQLException { } if (null != tableName) { try (Connection con = DriverManager.getConnection(connectionString); Statement statement = con.createStatement()) { - Utils.dropTableIfExists(tableName, statement); + TestUtils.dropTableIfExists(tableName, statement); } } } @@ -305,7 +301,7 @@ class Variables { final CountDownLatch latch = new CountDownLatch(3); try { sharedVariables.con = connect(); - if (Utils.isJDBC43OrGreater(sharedVariables.con)) { + if (TestUtils.isJDBC43OrGreater(sharedVariables.con)) { Thread thread1 = new Thread() { public void run() { try { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java index c29206c28..a7f19a6d7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java @@ -18,12 +18,12 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; @RunWith(JUnitPlatform.class) @@ -263,7 +263,7 @@ public void testSocketTimeout() throws Exception { private void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLException { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - Utils.dropProcedureIfExists(waitForDelaySPName, stmt); + TestUtils.dropProcedureIfExists(waitForDelaySPName, stmt); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java index 1ddfd947a..54f3600ff 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java @@ -23,8 +23,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -77,11 +77,11 @@ public static void terminateVariation() throws SQLException { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - Utils.dropTableIfExists(table1, stmt); - Utils.dropTableIfExists(table2, stmt); - Utils.dropTableIfExists(table3, stmt); - Utils.dropTableIfExists(table4, stmt); - Utils.dropTableIfExists(table5, stmt); + TestUtils.dropTableIfExists(table1, stmt); + TestUtils.dropTableIfExists(table2, stmt); + TestUtils.dropTableIfExists(table3, stmt); + TestUtils.dropTableIfExists(table4, stmt); + TestUtils.dropTableIfExists(table5, stmt); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index 7a4547581..739d99908 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -38,8 +38,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.StringUtils; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -77,7 +77,7 @@ public void testDatabaseMetaDataWrapper() throws SQLException { */ @Test public void testDriverVersion() throws SQLException, IOException { - String manifestFile = Utils.getCurrentClassPath() + "META-INF/MANIFEST.MF"; + String manifestFile = TestUtils.getCurrentClassPath() + "META-INF/MANIFEST.MF"; manifestFile = manifestFile.replace("test-classes", "classes"); File f = new File(manifestFile); @@ -200,7 +200,7 @@ public void testDBSchemasForDashedCatalogName() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - Utils.dropDatabaseIfExists(testCatalog, stmt); + TestUtils.dropDatabaseIfExists(testCatalog, stmt); stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); stmt.execute(String.format("USE [%s]", testCatalog)); @@ -232,7 +232,7 @@ public void testDBSchemasForDashedCatalogName() throws SQLException { MessageFormat dashCatalogFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); assertTrue(hasDashCatalogSchema, dashCatalogFormat.format(new Object[] {testSchema})); } finally { - Utils.dropDatabaseIfExists(testCatalog, stmt); + TestUtils.dropDatabaseIfExists(testCatalog, stmt); } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); @@ -253,7 +253,7 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { String testSchema = "some-schema" + id; try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - Utils.dropDatabaseIfExists(testCatalog, stmt); + TestUtils.dropDatabaseIfExists(testCatalog, stmt); stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); stmt.execute(String.format("USE [%s]", testCatalog)); @@ -279,7 +279,7 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { MessageFormat atLeastOneFoundFormat = new MessageFormat(TestResource.getResource("R_atLeastOneFound")); assertTrue(hasResults, atLeastOneFoundFormat.format(schemaMsgArgs)); } finally { - Utils.dropDatabaseIfExists(testCatalog, stmt); + TestUtils.dropDatabaseIfExists(testCatalog, stmt); } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java index 4cd0bcb4b..af5a227eb 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java @@ -22,8 +22,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -210,8 +210,8 @@ public void bulkCopyTestMoney() throws SQLException { public void bulkCopyTestSmallmoney() throws SQLException { String col1Value = "126.1230"; String destTableName = "dest_sqlVariant"; - Utils.dropTableIfExists(tableName, stmt); - Utils.dropTableIfExists(destTableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); stmt.executeUpdate( "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "smallmoney" + ") )"); @@ -265,8 +265,8 @@ public void bulkCopyTestTwoCols() throws SQLException { String col1Value = "2015-05-05"; String col2Value = "126.1230"; String destTableName = "dest_sqlVariant"; - Utils.dropTableIfExists(tableName, stmt); - Utils.dropTableIfExists(destTableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST ('" + col1Value + "' AS " + "date" + ")" + ",CAST (" + col2Value + " AS " + "smallmoney" + ") )"); @@ -427,7 +427,7 @@ public void bulkCopyTestBinary20() throws SQLException { rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); while (rs.next()) { - assertTrue(Utils.parseByte(rs.getBytes(1), col1Value.getBytes())); + assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } } @@ -450,7 +450,7 @@ public void bulkCopyTestVarbinary20() throws SQLException { rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); while (rs.next()) { - assertTrue(Utils.parseByte(rs.getBytes(1), col1Value.getBytes())); + assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } } @@ -472,7 +472,7 @@ public void bulkCopyTestVarbinary8000() throws SQLException { rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); while (rs.next()) { - assertTrue(Utils.parseByte(rs.getBytes(1), col1Value.getBytes())); + assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } } @@ -602,8 +602,8 @@ public void bulkCopyTestDatetime2() throws SQLException { public void bulkCopyTestTime() throws SQLException { String col1Value = "'12:26:27.1452367'"; String destTableName = "dest_sqlVariant"; - Utils.dropTableIfExists(tableName, stmt); - Utils.dropTableIfExists(destTableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); stmt.executeUpdate( "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "time(2)" + ") )"); @@ -671,8 +671,8 @@ public void bulkCopyTestVarChar8000() throws SQLException { } private void beforeEachSetup(String colType, Object colValue) throws SQLException { - Utils.dropTableIfExists(tableName, stmt); - Utils.dropTableIfExists(destTableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + "(col1) values (CAST (" + colValue + " AS " + colType + ") )"); stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); @@ -698,8 +698,8 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - Utils.dropTableIfExists(tableName, stmt); - Utils.dropTableIfExists(destTableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); if (null != stmt) { stmt.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java index 86e0b78f8..b06a1ed86 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java @@ -27,9 +27,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -166,7 +166,7 @@ public void testSetup() throws TestAbortedException, Exception { // by default to the connection. See issue https://github.com/Microsoft/mssql-jdbc/issues/559 connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); stmt = (SQLServerStatement) connection.createStatement(); - Utils.dropTableIfExists("dateandtime", stmt); + TestUtils.dropTableIfExists("dateandtime", stmt); String sql1 = "create table dateandtime (id integer not null, my_date date, my_time time, my_timestamp datetime2 constraint pk_esimple primary key (id))"; stmt.execute(sql1); @@ -187,7 +187,7 @@ public void testSetup() throws TestAbortedException, Exception { @AfterAll public static void terminateVariation() throws SQLException { - Utils.dropTableIfExists("dateandtime", stmt); + TestUtils.dropTableIfExists("dateandtime", stmt); if (null != connection) { connection.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java index 5dc76d12b..33b76e60e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java @@ -29,8 +29,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -985,14 +985,14 @@ public void testNull() throws SQLException { } private void beforeEachSetup() throws SQLException { - Utils.dropTableIfExists(geomTableName, stmt); - Utils.dropTableIfExists(geogTableName, stmt); + TestUtils.dropTableIfExists(geomTableName, stmt); + TestUtils.dropTableIfExists(geogTableName, stmt); stmt.executeUpdate("Create table " + geomTableName + " (c1 geometry)"); stmt.executeUpdate("Create table " + geogTableName + " (c1 geography)"); } private void beforeEachSetupSpatialDatatype() throws SQLException { - Utils.dropTableIfExists(spatialDatatypeTableName, stmt); + TestUtils.dropTableIfExists(spatialDatatypeTableName, stmt); stmt.executeUpdate("Create table " + spatialDatatypeTableName + " (c1 geometry," + "c2 geography," + "c3 nvarchar(512)," + "c4 decimal(28,4)," + "c5 int)"); } @@ -1071,8 +1071,8 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - Utils.dropTableIfExists(geomTableName, stmt); - Utils.dropTableIfExists(geogTableName, stmt); + TestUtils.dropTableIfExists(geomTableName, stmt); + TestUtils.dropTableIfExists(geogTableName, stmt); if (null != stmt) { stmt.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java index 3d5a3937d..cfb5729b4 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java @@ -23,14 +23,14 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomData; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomData; /** @@ -404,7 +404,7 @@ public void insertVarChar8001() throws SQLException { for (int i = 0; i < 8001; i++) { buffer.append("a"); } - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con .prepareStatement("insert into " + tableName + " values (?)"); @@ -520,7 +520,7 @@ public void updateBinary20() throws SQLException, SecurityException, IOException */ @Test public void insertTest() throws SQLException { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 int)"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con .prepareStatement("insert into " + tableName + " values (?, ?)"); @@ -551,7 +551,7 @@ public void insertTest() throws SQLException { */ @Test public void insertTestNull() throws SQLException { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values ( ?)"); @@ -571,7 +571,7 @@ public void insertTestNull() throws SQLException { */ @Test public void insertSetObject() throws SQLException { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values (?)"); @@ -591,11 +591,11 @@ public void insertSetObject() throws SQLException { @Test public void callableStatementOutputIntTest() throws SQLException { int value = 5; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value + " AS " + "int" + "))"); - Utils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + tableName; stmt.execute(sql); @@ -618,11 +618,11 @@ public void callableStatementOutputIntTest() throws SQLException { public void callableStatementOutputDateTest() throws SQLException { String value = "2015-05-08"; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + " values (CAST ('" + value + "' AS " + "date" + "))"); - Utils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + tableName; stmt.execute(sql); @@ -645,11 +645,11 @@ public void callableStatementOutputDateTest() throws SQLException { public void callableStatementOutputTimeTest() throws SQLException { String value = "12:26:27.123345"; String returnValue = "12:26:27"; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + " values (CAST ('" + value + "' AS " + "time(3)" + "))"); - Utils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + tableName; stmt.execute(sql); @@ -672,13 +672,13 @@ public void callableStatementOutputTimeTest() throws SQLException { public void callableStatementOutputBinaryTest() throws SQLException { byte[] binary20 = RandomData.generateBinaryTypes("20", false, false); byte[] secondBinary20 = RandomData.generateBinaryTypes("20", false, false); - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values (?,?)"); pstmt.setObject(1, binary20); pstmt.setObject(2, secondBinary20); pstmt.execute(); - Utils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1 "; stmt.execute(sql); @@ -703,11 +703,11 @@ public void callableStatementOutputBinaryTest() throws SQLException { public void callableStatementInputOutputIntTest() throws SQLException { int col1Value = 5; int col2Value = 2; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 int)"); stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" + "), " + col2Value + ")"); - Utils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1"; stmt.execute(sql); @@ -732,11 +732,11 @@ public void callableStatementInputOutputReturnIntTest() throws SQLException { int col1Value = 5; int col2Value = 2; int returnValue = 12; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 int)"); stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" + "), " + col2Value + ")"); - Utils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1" + " return " + returnValue; stmt.execute(sql); @@ -764,11 +764,11 @@ public void callableStatementInputOutputReturnStringTest() throws SQLException { String col2Value = "bb"; int returnValue = 12; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + "(col1,col2) values" + " (CAST ('" + col1Value + "' AS " + "varchar(5)" + ")" + " ,CAST ('" + col2Value + "' AS " + "varchar(5)" + ")" + ")"); - Utils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1 " + " return " + returnValue; stmt.execute(sql); @@ -795,7 +795,7 @@ public void readSeveralRows() throws SQLException { short value1 = 5; int value2 = 10; String value3 = "hi"; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant, col3 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value1 + " AS " + "tinyint" + ")" + ",CAST (" + value2 + " AS " + "int" + ")" + ",CAST ('" + value3 + "' AS " + "char(2)" + ")" + ")"); @@ -879,7 +879,7 @@ private boolean parseByte(byte[] expectedData, byte[] retrieved) { * @throws SQLException */ private void createAndPopulateTable(String columnType, Object value) throws SQLException { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value + " AS " + columnType + "))"); } @@ -904,8 +904,8 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - Utils.dropProcedureIfExists(inputProc, stmt); - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropProcedureIfExists(inputProc, stmt); + TestUtils.dropTableIfExists(tableName, stmt); if (null != stmt) { stmt.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 1c3f8dc52..b5aaaf964 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -21,6 +21,7 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomData; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; @@ -28,10 +29,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.sqlType.SqlDate; -import com.microsoft.sqlserver.testframework.util.RandomData; @RunWith(JUnitPlatform.class) @@ -469,8 +469,8 @@ public void testSetup() throws SQLException { .getConnection(connectionString + ";sendStringParametersAsUnicode=true;"); stmt = (SQLServerStatement) conn.createStatement(); - Utils.dropProcedureIfExists(procedureName, stmt); - Utils.dropTableIfExists(destTable, stmt); + TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropTableIfExists(destTable, stmt); dropTVPS(); createTVPS(); @@ -502,8 +502,8 @@ private void createTVPS() throws SQLException { @AfterEach public void terminateVariation() throws SQLException { - Utils.dropProcedureIfExists(procedureName, stmt); - Utils.dropTableIfExists(destTable, stmt); + TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropTableIfExists(destTable, stmt); dropTVPS(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java index d7cc3c310..01bcebb0b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java @@ -19,8 +19,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerBulkCSVFileRecord; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -34,7 +34,7 @@ public class ExceptionTest extends AbstractTest { */ @Test public void testBulkCSVFileRecordExceptionCause() throws Exception { - String filePath = Utils.getCurrentClassPath(); + String filePath = TestUtils.getCurrentClassPath(); try { SQLServerBulkCSVFileRecord scvFileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, @@ -66,7 +66,7 @@ public void testSocketTimeoutExceptionCause() throws Exception { try { conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - Utils.dropProcedureIfExists(waitForDelaySPName, conn.createStatement()); + TestUtils.dropProcedureIfExists(waitForDelaySPName, conn.createStatement()); createWaitForDelayPreocedure(conn); conn = (SQLServerConnection) DriverManager diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java index 8539439cd..46c69ec81 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java @@ -21,7 +21,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.Utils;; +import com.microsoft.sqlserver.jdbc.TestUtils;; /** @@ -72,20 +72,20 @@ public static void populateProperties() { public void testFIPSOnOracle() throws Exception { assumeTrue(ORACLE_JVM.equals(currentJVM), TestResource.getResource("R_wrongEnv") + ORACLE_JVM); - assumeTrue("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), + assumeTrue("FIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), TestResource.getResource("R_fipsPropertyNotSet")); assertTrue(isFIPS("SunJSSE"), "FIPS " + TestResource.getResource("R_shouldBeEnabled")); // As JDK 1.7 is not supporting lambda for time being commenting. /* - * assumingThat("NSSFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> + * assumingThat("NSSFIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> * assertTrue(isFIPS("SunJSSE"), TestResource.getResource("R_shouldBeEnabled")), () -> * assertTrue(isFIPS("SunPKCS11-NSS"), "Testing"))); - * assumingThat("BCFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> + * assumingThat("BCFIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> * assertTrue(isFIPS("SunJSSE"), TestResource.getResource("R_shouldBeEnabled")), () -> * assertTrue(isFIPS("BCFIPS"), "Testing"))); - * assumingThat("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), ()-> assertTrue(isFIPS("SunJSSE"), + * assumingThat("FIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), ()-> assertTrue(isFIPS("SunJSSE"), * TestResource.getResource("R_shouldBeEnabled"))); */ } @@ -99,19 +99,19 @@ public void testFIPSOnOracle() throws Exception { public void testFIPSOnIBM() throws Exception { assumeTrue(IBM_JVM.equals(currentJVM), TestResource.getResource("R_wrongEnv") + IBM_JVM); - assumeTrue("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), + assumeTrue("FIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), TestResource.getResource("R_fipsPropertyNotSet")); assertTrue(isFIPS("IBMJCEFIP"), "FIPS " + TestResource.getResource("R_shouldBeEnabled")); // As JDK 1.7 is not supporting lambda for time being commenting. /* - * assumingThat("NSSFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> + * assumingThat("NSSFIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), () -> assertAll("All FIPS", () -> * assertTrue(isFIPS("IBMJCEFIP"), "FIPS should be Enabled."), () -> assertTrue(isFIPS("SunPKCS11-NSS"), - * "Testing"))); assumingThat("BCFIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), () -> + * "Testing"))); assumingThat("BCFIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), () -> * assertAll("All FIPS", () -> assertTrue(isFIPS("IBMJCEFIPS"), "FIPS should be Enabled."), () -> * assertTrue(isFIPS("BCFIPS"), "Testing"))); - * assumingThat("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), ()-> assertTrue(isFIPS("IBMJCEFIPS"), + * assumingThat("FIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), ()-> assertTrue(isFIPS("IBMJCEFIPS"), * "FIPS Should be enabled")); */ } @@ -123,7 +123,7 @@ public void testFIPSOnIBM() throws Exception { @Test @Disabled public void testFIPSEnv() { - assumeTrue("FIPS".equals(Utils.getConfiguredProperty("FIPS_ENV")), + assumeTrue("FIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), TestResource.getResource("R_fipsPropertyNotSet")); // As JDK 1.7 is not supporting lambda for time being commenting. diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java index 962f454b7..787d75274 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java @@ -19,8 +19,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.StringUtils; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.PrepUtil; -import com.microsoft.sqlserver.testframework.Utils;; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.PrepUtil;; /** @@ -34,7 +34,7 @@ public class FipsTest { @BeforeAll public static void init() { - connectionString = Utils.getConfiguredProperty("mssql_jdbc_test_connection_properties"); + connectionString = TestUtils.getConfiguredProperty("mssql_jdbc_test_connection_properties"); dataSourceProps = getDataSourceProperties(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java index 81bf36465..d821c876d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java @@ -18,9 +18,9 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; @RunWith(JUnitPlatform.class) @@ -46,7 +46,7 @@ public void testParameterMetaDataWrapper() throws SQLException { assertSame(parameterMetaData, parameterMetaData.unwrap(ParameterMetaData.class)); } } finally { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } } } @@ -85,7 +85,7 @@ public void testNameWithBraces() throws SQLException { pstmt.getParameterMetaData(); } } finally { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java index 7f23ff551..2cb73ee5b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java @@ -19,10 +19,10 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; @RunWith(JUnitPlatform.class) @@ -40,7 +40,7 @@ public static void BeforeTests() throws SQLException { @AfterAll public static void dropTables() throws SQLException { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); if (null != stmt) { stmt.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java index 60baafb42..705815d51 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java @@ -29,8 +29,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -346,7 +346,7 @@ public void testSquareBracketAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - Utils.dropTableIfExists(squareBracketTableName, stmt); + TestUtils.dropTableIfExists(squareBracketTableName, stmt); String createTable = "create table " + squareBracketTableName + " (c1 int)"; stmt.execute(createTable); @@ -374,7 +374,7 @@ public void testDoubleQuoteAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - Utils.dropTableIfExists(doubleQuoteTableName, stmt); + TestUtils.dropTableIfExists(doubleQuoteTableName, stmt); String createTable = "create table " + doubleQuoteTableName + " (c1 int)"; stmt.execute(createTable); @@ -403,7 +403,7 @@ public void testSchemaAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - Utils.dropTableIfExists("[dbo]." + squareBracketTableName, stmt); + TestUtils.dropTableIfExists("[dbo]." + squareBracketTableName, stmt); String createTable = "create table " + schemaTableName + " (c1 int)"; stmt.execute(createTable); @@ -432,7 +432,7 @@ public void testColumnNameMixAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - Utils.dropTableIfExists(squareBracketTableName, stmt); + TestUtils.dropTableIfExists(squareBracketTableName, stmt); String createTable = "create table " + squareBracketTableName + " ([c]]]]1] int, [c]]]]2] int)"; stmt.execute(createTable); @@ -602,7 +602,7 @@ public void testNonSupportedColumns() throws Exception { f1.setAccessible(true); f1.set(connection, true); - Utils.dropTableIfExists(unsupportedTableName, stmt); + TestUtils.dropTableIfExists(unsupportedTableName, stmt); String createTable = "create table " + unsupportedTableName + " (c1 geometry, c2 geography, c3 datetime, c4 smalldatetime)"; @@ -635,7 +635,7 @@ public void testSetup() throws TestAbortedException, Exception { try (Connection connection = DriverManager .getConnection(connectionString + ";useBulkCopyForBatchInsert=true;")) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); String sql1 = "create table " + tableName + " " + "(" + "c1 int DEFAULT 1234, " + "c2 bit, " + "c3 char DEFAULT NULL, " + "c4 date, " + "c5 datetime2, " + "c6 float, " + "c7 nchar, " + "c8 varchar(20), " + "c9 varchar(max)" + ")"; @@ -649,10 +649,10 @@ public void testSetup() throws TestAbortedException, Exception { public static void terminateVariation() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString)) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { - Utils.dropTableIfExists(tableName, stmt); - Utils.dropTableIfExists(squareBracketTableName, stmt); - Utils.dropTableIfExists(doubleQuoteTableName, stmt); - Utils.dropTableIfExists(unsupportedTableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(squareBracketTableName, stmt); + TestUtils.dropTableIfExists(doubleQuoteTableName, stmt); + TestUtils.dropTableIfExists(unsupportedTableName, stmt); } } } 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 5d3f9cc77..a41cf3c47 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -24,9 +24,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -112,7 +112,7 @@ public void testSetup() throws TestAbortedException, Exception { connection = DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) connection.createStatement(); - Utils.dropTableIfExists("esimple", stmt); + TestUtils.dropTableIfExists("esimple", stmt); String sql1 = "create table esimple (id integer not null, name varchar(255), constraint pk_esimple primary key (id))"; stmt.execute(sql1); stmt.close(); @@ -122,7 +122,7 @@ public void testSetup() throws TestAbortedException, Exception { public static void terminateVariation() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - Utils.dropTableIfExists("esimple", stmt); + TestUtils.dropTableIfExists("esimple", stmt); } if (null != pstmt) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java index 942f0b248..0d5422458 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java @@ -24,8 +24,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -46,7 +46,7 @@ public class RegressionTest extends AbstractTest { public static void setupTest() throws SQLException { con = DriverManager.getConnection(connectionString); try (Statement stmt = con.createStatement()) { - Utils.dropTableIfExists("x", stmt); + TestUtils.dropTableIfExists("x", stmt); } } @@ -164,7 +164,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { Statement stmt = con.createStatement(); ResultSet rs = null; - Utils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists("TEST_TABLE", stmt); con.setAutoCommit(false); @@ -246,7 +246,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } } } finally { - Utils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists("TEST_TABLE", stmt); if (null != stmt) { stmt.close(); } @@ -263,7 +263,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { public void addBatchWithLargeStringTest() throws SQLException { Statement stmt = con.createStatement(); PreparedStatement pstmt = null; - Utils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists("TEST_TABLE", stmt); con.setAutoCommit(false); @@ -339,7 +339,7 @@ public void addBatchWithLargeStringTest() throws SQLException { catch (Exception e) { fail(e.toString()); } finally { - Utils.dropTableIfExists("testTable", stmt); + TestUtils.dropTableIfExists("testTable", stmt); if (null != stmt) { stmt.close(); } @@ -354,8 +354,8 @@ public void addBatchWithLargeStringTest() throws SQLException { @AfterAll public static void cleanup() throws SQLException { try (Statement stmt = con.createStatement()) { - Utils.dropTableIfExists("x", stmt); - Utils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists("x", stmt); + TestUtils.dropTableIfExists("TEST_TABLE", stmt); } if (null != con) { con.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java index a59187826..eb9bd0c3e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java @@ -14,12 +14,11 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.jdbc.dataclassification.SensitivityProperty; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; -import com.microsoft.sqlserver.testframework.util.Util; @RunWith(JUnitPlatform.class) @@ -36,10 +35,10 @@ public void testDataClassificationMetadata() throws Exception { // Run this test only with newer SQL Servers (version>=2018) that support Data Classification try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement();) { - if (Util.serverSupportsDataClassification(stmt)) { + if (TestUtils.serverSupportsDataClassification(stmt)) { createTable(connection, stmt); runTestsForServer(stmt); - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java index 4876c0689..845f4a057 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java @@ -32,9 +32,9 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.ISQLServerResultSet; +import com.microsoft.sqlserver.jdbc.RandomUtil; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; @RunWith(JUnitPlatform.class) @@ -278,7 +278,7 @@ public void testGetObjectAsLocalDateTime() throws SQLException { LocalTime actualLocalTime = rs.getObject(1, LocalTime.class); assertEquals(expectedLocalTime, actualLocalTime); } finally { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); TimeZone.setDefault(prevTimeZone); } } @@ -303,7 +303,7 @@ public void testResultSetWrapper() throws SQLException { assertSame(rs, rs.unwrap(ResultSet.class)); assertSame(rs, rs.unwrap(ISQLServerResultSet.class)); } finally { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java index b95a7254b..cc676cdbb 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java @@ -16,17 +16,17 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.ComparisonUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.sqlType.SqlType; -import com.microsoft.sqlserver.testframework.util.ComparisonUtil; @RunWith(JUnitPlatform.class) @@ -169,7 +169,7 @@ private void setupVariation(boolean setSelectMethod, Integer resultSetType, Inte stmt = conn.createStatement(); } - Utils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropProcedureIfExists(procedureName, stmt); dropTVPS(tvpName); DBConnection dbConnection = new DBConnection(connectionString); @@ -188,9 +188,9 @@ private void setupVariation(boolean setSelectMethod, Integer resultSetType, Inte } private void terminateVariation() throws SQLException { - Utils.dropProcedureIfExists(procedureName, stmt); - Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); - Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); + TestUtils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); dropTVPS(tvpName); if (null != stmt) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java index 5b128ec39..7be7aee1d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java @@ -24,8 +24,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils;; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractTest;; @RunWith(JUnitPlatform.class) @@ -133,13 +133,13 @@ public static void beforeAll() throws SQLException { stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_varcharMax + "') " + " drop type " + tvp_varcharMax); - Utils.dropTableIfExists(srcTable_varcharMax, stmt); - Utils.dropTableIfExists(desTable_varcharMax, stmt); + TestUtils.dropTableIfExists(srcTable_varcharMax, stmt); + TestUtils.dropTableIfExists(desTable_varcharMax, stmt); stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_time_6 + "') " + " drop type " + tvp_time_6); - Utils.dropTableIfExists(srcTable_time_6, stmt); - Utils.dropTableIfExists(desTable_time_6, stmt); + TestUtils.dropTableIfExists(srcTable_time_6, stmt); + TestUtils.dropTableIfExists(desTable_time_6, stmt); String sql = "create table " + srcTable_varcharMax + " (c1 varchar(max) null);"; stmt.execute(sql); @@ -185,7 +185,7 @@ private static void populateTime6SrcTable() throws SQLException { } private static void dropProcedure() throws SQLException { - Utils.dropProcedureIfExists(spName_varcharMax, stmt); + TestUtils.dropProcedureIfExists(spName_varcharMax, stmt); } private static void createPreocedure() throws SQLException { @@ -200,13 +200,13 @@ public static void terminateVariation() throws SQLException { dropProcedure(); stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_varcharMax + "') " + " drop type " + tvp_varcharMax); - Utils.dropTableIfExists(srcTable_varcharMax, stmt); - Utils.dropTableIfExists(desTable_varcharMax, stmt); + TestUtils.dropTableIfExists(srcTable_varcharMax, stmt); + TestUtils.dropTableIfExists(desTable_varcharMax, stmt); stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_time_6 + "') " + " drop type " + tvp_time_6); - Utils.dropTableIfExists(srcTable_time_6, stmt); - Utils.dropTableIfExists(desTable_time_6, stmt); + TestUtils.dropTableIfExists(srcTable_time_6, stmt); + TestUtils.dropTableIfExists(desTable_time_6, stmt); if (null != stmt) { stmt.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java index d8104c130..c004db9c0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java @@ -25,8 +25,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -357,8 +357,8 @@ private static void populateSourceTable() throws SQLException { } private static void dropTables() throws SQLException { - Utils.dropTableIfExists(srcTable, stmt); - Utils.dropTableIfExists(desTable, stmt); + TestUtils.dropTableIfExists(srcTable, stmt); + TestUtils.dropTableIfExists(desTable, stmt); } private static void createTables() throws SQLException { @@ -383,7 +383,7 @@ private static void dropTVPS() throws SQLException { } private static void dropProcedure() throws SQLException { - Utils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropProcedureIfExists(procedureName, stmt); } private static void createPreocedure() throws SQLException { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java index 7a44ea701..43b618c76 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java @@ -17,10 +17,10 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerSavepoint; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.util.RandomUtil; /** diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java index 3c2262214..10dd7472c 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java @@ -22,11 +22,11 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.PrepUtil; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -45,7 +45,7 @@ public class UTF8SupportTest extends AbstractTest { */ @Test public void testChar() throws SQLException { - if (Utils.serverSupportsUTF8(connection)) { + if (TestUtils.serverSupportsUTF8(connection)) { createTable("char(10)"); validate("teststring"); // This is 10 UTF-8 bytes. D1 82 D0 B5 D1 81 D1 82 31 32 @@ -77,7 +77,7 @@ public void testChar() throws SQLException { */ @Test public void testVarchar() throws SQLException { - if (Utils.serverSupportsUTF8(connection)) { + if (TestUtils.serverSupportsUTF8(connection)) { createTable("varchar(10)"); validate("teststring"); validate("тест12"); @@ -108,7 +108,7 @@ public void testVarchar() throws SQLException { @BeforeAll public static void setUp() throws ClassNotFoundException, SQLException { connection = PrepUtil.getConnection(getConfiguredProperty("mssql_jdbc_test_connection_properties")); - if (Utils.serverSupportsUTF8(connection)) { + if (TestUtils.serverSupportsUTF8(connection)) { databaseName = RandomUtil.getIdentifier("UTF8Database"); tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundaryTable")); createDatabaseWithUTF8Collation(); @@ -119,8 +119,8 @@ public static void setUp() throws ClassNotFoundException, SQLException { @AfterAll public static void cleanUp() throws SQLException { try (Statement stmt = connection.createStatement()) { - if (Utils.serverSupportsUTF8(connection)) { - Utils.dropDatabaseIfExists(databaseName, stmt); + if (TestUtils.serverSupportsUTF8(connection)) { + TestUtils.dropDatabaseIfExists(databaseName, stmt); } } if (null != connection) { @@ -137,7 +137,7 @@ private static void createDatabaseWithUTF8Collation() throws SQLException { private static void createTable(String columnType) throws SQLException { try (Statement stmt = connection.createStatement();) { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate("CREATE TABLE " + tableName + " (c " + columnType + ")"); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java index f1d34acf2..b718ec046 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java @@ -37,7 +37,11 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.jdbc.TestUtils.DBBinaryStream; +import com.microsoft.sqlserver.jdbc.TestUtils.DBCharacterStream; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBCoercion; @@ -47,11 +51,7 @@ 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.Utils.DBBinaryStream; -import com.microsoft.sqlserver.testframework.Utils.DBCharacterStream; import com.microsoft.sqlserver.testframework.sqlType.SqlType; -import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -709,13 +709,13 @@ private Object createLob(Class lobClass) { else if (lobClass == DBBinaryStream.class) return new DBInvalidUtil().new InvalidBinaryStream(data, streamLength < -1); if (lobClass == Clob.class) { - ArrayList types = Utils.types(); - SqlType type = Utils.find(String.class); + ArrayList types = TestUtils.types(); + SqlType type = TestUtils.find(String.class); Object expected = type.createdata(String.class, data); return new DBInvalidUtil().new InvalidClob(expected, false); } else { - ArrayList types = Utils.types(); - SqlType type = Utils.find(byte[].class); + ArrayList types = TestUtils.types(); + SqlType type = TestUtils.find(byte[].class); Object expected = type.createdata(type.getClass(), data); return new DBInvalidUtil().new InvalidBlob(expected, false); } @@ -729,10 +729,10 @@ private static DBTable createTable(DBTable table, String[] types, boolean popula table = new DBTable(false); // Add RowId - table.addColumn(Utils.find("int")); + table.addColumn(TestUtils.find("int")); for (String type1 : types) { - SqlType type = Utils.find(type1); + SqlType type = TestUtils.find(type1); table.addColumn(type); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java index 6371383d6..e422bfbc1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java @@ -26,13 +26,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -139,7 +139,7 @@ private void Repro47239Internal(String mode) throws Exception { try (Statement stmt = conn.createStatement()) { try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (Exception ignored) {} stmt.executeUpdate("create table " + tableName + " (c1_int int, c2_varchar varchar(20), c3_date datetime, c4_int int identity(1,1) primary key)"); @@ -307,7 +307,7 @@ private void Repro47239Internal(String mode) throws Exception { private void Repro47239largeInternal(String mode) throws Exception { - assumeTrue("JDBC42".equals(Utils.getConfiguredProperty("JDBC_Version")), + assumeTrue("JDBC42".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); // the DBConnection for detecting whether the server is SQL Azure or SQL Server. con = DriverManager.getConnection(connectionString); @@ -350,7 +350,7 @@ private void Repro47239largeInternal(String mode) throws Exception { try (Statement stmt = conn.createStatement()) { try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (Exception ignored) {} try { stmt.executeLargeUpdate("create table " + tableName diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java index 9f9ee64c9..264f2fa36 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java @@ -26,9 +26,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -228,8 +228,8 @@ private static void dropTable() throws SQLException { try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - Utils.dropTableIfExists("ctstable2", stmt); - Utils.dropTableIfExists("ctstable1", stmt); + TestUtils.dropTableIfExists("ctstable2", stmt); + TestUtils.dropTableIfExists("ctstable1", stmt); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java index 69b8cf2ea..b72cda221 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java @@ -22,8 +22,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -127,7 +127,7 @@ public static void testSetup() throws TestAbortedException, Exception { */ private static void dropTable() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } } 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 33bda0a9b..9566e0d36 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 @@ -18,11 +18,11 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; 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; /** @@ -105,7 +105,7 @@ public void datatypesTest() throws SQLException { * @throws SQLException */ private void terminateVariation(Statement statement) throws SQLException { - Utils.dropTableIfExists(tableName, statement); - Utils.dropProcedureIfExists(procName, statement); + TestUtils.dropTableIfExists(tableName, statement); + TestUtils.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 3a1461179..197e2787e 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 @@ -28,8 +28,8 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -779,10 +779,10 @@ public static void afterAll() throws Exception { Statement stmt = conn.createStatement(); try { - Utils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); - Utils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); - Utils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); - Utils.dropTableIfExists("UnitStatement_LimitEscape_t4", stmt); + TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); + TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); + TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); + TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t4", stmt); } catch (Exception ex) { fail(ex.toString()); } finally { 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 335f1283e..5e5c0ffb1 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 @@ -19,10 +19,10 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -81,7 +81,7 @@ public static void afterAll() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - Utils.dropTableIfExists("dbo.CricketTeams", stmt); + TestUtils.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 cf28d2402..b50b36278 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 @@ -20,8 +20,8 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -42,7 +42,7 @@ public class NamedParamMultiPartTest extends AbstractTest { public static void beforeAll() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement()) { - Utils.dropProcedureIfExists("mystoredproc", statement); + TestUtils.dropProcedureIfExists("mystoredproc", statement); statement.executeUpdate( "CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); } @@ -156,7 +156,7 @@ public void update6() throws Exception { public static void afterAll() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - Utils.dropProcedureIfExists("mystoredproc", stmt); + TestUtils.dropProcedureIfExists("mystoredproc", stmt); } } } 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 79fd32e6b..bf6680f3d 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 @@ -22,13 +22,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerParameterMetaData; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; 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; /** @@ -1370,17 +1370,17 @@ public void testComplexQueryWithMultipleTables() throws SQLException { */ @AfterAll public static void dropTables() throws SQLException { - 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); + TestUtils.dropTableIfExists(nameTable, stmt); + TestUtils.dropTableIfExists(phoneNumberTable, stmt); + TestUtils.dropTableIfExists(mergeNameDesTable, stmt); + TestUtils.dropTableIfExists(numericTable, stmt); + TestUtils.dropTableIfExists(phoneNumberTable, stmt); + TestUtils.dropTableIfExists(charTable, stmt); + TestUtils.dropTableIfExists(charTable2, stmt); + TestUtils.dropTableIfExists(binaryTable, stmt); + TestUtils.dropTableIfExists(dateAndTimeTable, stmt); + TestUtils.dropTableIfExists(multipleTypesTable, stmt); + TestUtils.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 7b8d1f6b1..cd9bd0a2e 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 @@ -24,8 +24,8 @@ import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.Utils; /** @@ -93,7 +93,7 @@ public void poolableTest() throws SQLException, ClassNotFoundException { public static void afterAll() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { try { - Utils.dropProcedureIfExists("ProcName", stmt); + TestUtils.dropProcedureIfExists("ProcName", stmt); } catch (Exception ex) { fail(ex.toString()); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java index ba9c39e0a..695155a9c 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java @@ -24,9 +24,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.Utils; @RunWith(JUnitPlatform.class) @@ -133,7 +133,7 @@ public void testSelectIntoUpdateCount() throws SQLException { */ @Test public void testUpdateQuery() throws SQLException { - assumeTrue("JDBC41".equals(Utils.getConfiguredProperty("JDBC_Version")), + assumeTrue("JDBC41".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); @@ -143,7 +143,7 @@ public void testUpdateQuery() throws SQLException { int rows = 3; final String tableName = "[updateQuery]"; - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); stmt.executeUpdate( "CREATE TABLE " + tableName + " (" + "c1 int null," + "PK int NOT NULL PRIMARY KEY" + ")"); @@ -193,7 +193,7 @@ public void testUpdateQuery() throws SQLException { */ @Test public void testXmlQuery() throws SQLException { - assumeTrue("JDBC41".equals(Utils.getConfiguredProperty("JDBC_Version")), + assumeTrue("JDBC41".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); try (Connection connection = DriverManager.getConnection(connectionString); @@ -237,8 +237,8 @@ private void createTable(Statement stmt) throws SQLException { public static void terminate() throws SQLException { try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - Utils.dropTableIfExists(tableName, stmt); - Utils.dropProcedureIfExists(procName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropProcedureIfExists(procName, stmt); } } } 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 fc9bde06b..5c66a9722 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 @@ -41,16 +41,16 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.SQLServerResultSetMetaData; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.Utils; -import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -79,7 +79,7 @@ public void init() throws Exception { con.setAutoCommit(false); try (Statement stmt = con.createStatement()) { try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) {} stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT PRIMARY KEY, col2 VARCHAR(" + TEST_STRING.length() + "))"); @@ -96,7 +96,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) {} } } @@ -215,7 +215,7 @@ public void testQueryTimeout() throws Exception { */ @Test public void testCancelLongResponse() throws Exception { - assumeTrue("JDBC42".equals(Utils.getConfiguredProperty("JDBC_Version")), + assumeTrue("JDBC42".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con @@ -657,7 +657,7 @@ public void testCancelGetOutParams() throws Exception { Statement stmt = con.createStatement()) { try { - Utils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(procName, stmt); } catch (Exception ex) {} ; stmt.executeUpdate("CREATE PROCEDURE " + procName + " @arg1 CHAR(512) OUTPUT, " + " @arg2 CHAR(512) OUTPUT, " + " @arg3 CHAR(512) OUTPUT " + "AS " + "BEGIN " @@ -691,7 +691,7 @@ public void testCancelGetOutParams() throws Exception { // Reexecute to prove CS is still good after last cancel cstmt.execute(); - Utils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(procName, stmt); } } @@ -998,10 +998,10 @@ public void testConsecutiveQueries() throws Exception { } try { - Utils.dropTableIfExists(table1Name, stmt); + TestUtils.dropTableIfExists(table1Name, stmt); } catch (SQLException e) {} try { - Utils.dropTableIfExists(table2Name, stmt); + TestUtils.dropTableIfExists(table2Name, stmt); } catch (SQLException e) {} stmt.executeUpdate("CREATE TABLE " + table1Name + " (col1 INT PRIMARY KEY)"); @@ -1021,7 +1021,7 @@ public void testConsecutiveQueries() throws Exception { */ @Test public void testLargeMaxRowsJDBC41() throws Exception { - assumeTrue("JDBC41".equals(Utils.getConfiguredProperty("JDBC_Version")), + assumeTrue("JDBC41".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); try (Connection con = DriverManager.getConnection(connectionString); @@ -1052,7 +1052,7 @@ public void testLargeMaxRowsJDBC41() throws Exception { */ @Test public void testLargeMaxRowsJDBC42() throws Exception { - assumeTrue("JDBC42".equals(Utils.getConfiguredProperty("JDBC_Version")), + assumeTrue("JDBC42".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); try (Connection con = DriverManager.getConnection(connectionString); @@ -1100,8 +1100,8 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - Utils.dropTableIfExists(table1Name, stmt); - Utils.dropTableIfExists(table2Name, stmt); + TestUtils.dropTableIfExists(table1Name, stmt); + TestUtils.dropTableIfExists(table2Name, stmt); } catch (SQLException e) {} } } @@ -1258,7 +1258,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - Utils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(procName, stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1607,8 +1607,8 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - Utils.dropTableIfExists(tableName, stmt); - Utils.dropProcedureIfExists(procName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropProcedureIfExists(procName, stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1645,7 +1645,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1820,7 +1820,7 @@ public void testNBCRowForAllNulls() throws Exception { con = ds.getConnection(); Statement stmt = con.createStatement(); try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) {} String createTableQuery = "CREATE TABLE " + tableName + "(col1 int PRIMARY KEY IDENTITY(1,1)"; @@ -1866,7 +1866,7 @@ public void testNBCROWWithRandomAccess() throws Exception { con = ds.getConnection(); Statement stmt = con.createStatement(); try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) {} // construct a query to create a table with 100 columns @@ -2261,9 +2261,9 @@ 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); + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(table2Name, stmt); + TestUtils.dropProcedureIfExists(sprocName, stmt); } catch (SQLException e) { fail(e.toString()); } @@ -2464,7 +2464,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) { fail(e.toString()); } @@ -2534,7 +2534,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - Utils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) { fail(e.toString()); } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java b/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java index e1e451df0..3f51817d8 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.BeforeAll; import com.microsoft.sqlserver.jdbc.SQLServerConnection; +import com.microsoft.sqlserver.jdbc.TestUtils; /** @@ -123,7 +124,7 @@ public static void teardown() throws Exception { * @return Value */ public static String getConfiguredProperty(String key) { - return Utils.getConfiguredProperty(key); + return TestUtils.getConfiguredProperty(key); } /** @@ -133,7 +134,7 @@ public static String getConfiguredProperty(String key) { * @return Value */ public static String getConfiguredProperty(String key, String defaultValue) { - return Utils.getConfiguredProperty(key, defaultValue); + return TestUtils.getConfiguredProperty(key, defaultValue); } /** diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBInvalidUtil.java b/src/test/java/com/microsoft/sqlserver/testframework/DBInvalidUtil.java index 948519026..21afe445f 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBInvalidUtil.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBInvalidUtil.java @@ -18,8 +18,8 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; -import com.microsoft.sqlserver.testframework.Utils.DBBinaryStream; -import com.microsoft.sqlserver.testframework.Utils.DBCharacterStream; +import com.microsoft.sqlserver.jdbc.TestUtils.DBBinaryStream; +import com.microsoft.sqlserver.jdbc.TestUtils.DBCharacterStream; /** diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java index 8a76fde82..08717c58c 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java @@ -20,8 +20,9 @@ import java.util.logging.Level; import java.util.logging.Logger; -import com.microsoft.sqlserver.testframework.Utils.DBBinaryStream; -import com.microsoft.sqlserver.testframework.Utils.DBCharacterStream; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.jdbc.TestUtils.DBBinaryStream; +import com.microsoft.sqlserver.jdbc.TestUtils.DBCharacterStream; /** @@ -328,7 +329,7 @@ public void verifydata(int ordinal, Class coercion, Object expectedData, Object break; case java.sql.Types.BINARY: - assertTrue(Utils.parseByte((byte[]) expectedData, (byte[]) retrieved), + assertTrue(TestUtils.parseByte((byte[]) expectedData, (byte[]) retrieved), " unexpected BINARY value, expected: " + expectedData + " ,received: " + retrieved); break; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java b/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java index f46fe62a6..b3b77b7fd 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBTable.java @@ -16,9 +16,9 @@ import java.util.logging.Level; import java.util.logging.Logger; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.testframework.sqlType.SqlType; import com.microsoft.sqlserver.testframework.sqlType.VariableLengthType; -import com.microsoft.sqlserver.testframework.util.RandomUtil; /** diff --git a/src/test/java/com/microsoft/sqlserver/testframework/Utils.java b/src/test/java/com/microsoft/sqlserver/testframework/Utils.java deleted file mode 100644 index 4b79735a5..000000000 --- a/src/test/java/com/microsoft/sqlserver/testframework/Utils.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * 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.testframework; - -import static org.junit.Assert.fail; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.CharArrayReader; -import java.net.URI; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.microsoft.sqlserver.testframework.sqlType.SqlBigInt; -import com.microsoft.sqlserver.testframework.sqlType.SqlBinary; -import com.microsoft.sqlserver.testframework.sqlType.SqlBit; -import com.microsoft.sqlserver.testframework.sqlType.SqlChar; -import com.microsoft.sqlserver.testframework.sqlType.SqlDate; -import com.microsoft.sqlserver.testframework.sqlType.SqlDateTime; -import com.microsoft.sqlserver.testframework.sqlType.SqlDateTime2; -import com.microsoft.sqlserver.testframework.sqlType.SqlDateTimeOffset; -import com.microsoft.sqlserver.testframework.sqlType.SqlDecimal; -import com.microsoft.sqlserver.testframework.sqlType.SqlFloat; -import com.microsoft.sqlserver.testframework.sqlType.SqlInt; -import com.microsoft.sqlserver.testframework.sqlType.SqlMoney; -import com.microsoft.sqlserver.testframework.sqlType.SqlNChar; -import com.microsoft.sqlserver.testframework.sqlType.SqlNVarChar; -import com.microsoft.sqlserver.testframework.sqlType.SqlNVarCharMax; -import com.microsoft.sqlserver.testframework.sqlType.SqlNumeric; -import com.microsoft.sqlserver.testframework.sqlType.SqlReal; -import com.microsoft.sqlserver.testframework.sqlType.SqlSmallDateTime; -import com.microsoft.sqlserver.testframework.sqlType.SqlSmallInt; -import com.microsoft.sqlserver.testframework.sqlType.SqlSmallMoney; -import com.microsoft.sqlserver.testframework.sqlType.SqlTime; -import com.microsoft.sqlserver.testframework.sqlType.SqlTinyInt; -import com.microsoft.sqlserver.testframework.sqlType.SqlType; -import com.microsoft.sqlserver.testframework.sqlType.SqlVarBinary; -import com.microsoft.sqlserver.testframework.sqlType.SqlVarBinaryMax; -import com.microsoft.sqlserver.testframework.sqlType.SqlVarChar; -import com.microsoft.sqlserver.testframework.sqlType.SqlVarCharMax; - - -/** - * Generic Utility class which we can access by test classes. - * - * @since 6.1.2 - */ -public class Utils { - public static final Logger log = Logger.getLogger("Utils"); - - // 'SQL' represents SQL Server, while 'SQLAzure' represents SQL Azure. - public static final String SERVER_TYPE_SQL_SERVER = "SQL"; - public static final String SERVER_TYPE_SQL_AZURE = "SQLAzure"; - // private static SqlType types = null; - private static ArrayList types = null; - - /** - * Returns serverType - * - * @return - */ - public static String getServerType() { - String serverType = null; - - String serverTypeProperty = getConfiguredProperty("server.type"); - if (null == serverTypeProperty) { - // default to SQL Server - serverType = SERVER_TYPE_SQL_SERVER; - } else if (serverTypeProperty.equalsIgnoreCase(SERVER_TYPE_SQL_AZURE)) { - serverType = SERVER_TYPE_SQL_AZURE; - } else if (serverTypeProperty.equalsIgnoreCase(SERVER_TYPE_SQL_SERVER)) { - serverType = SERVER_TYPE_SQL_SERVER; - } else { - if (log.isLoggable(Level.FINE)) { - log.fine("Server.type '" + serverTypeProperty + "' is not supported yet. Default to SQL Server"); - } - serverType = SERVER_TYPE_SQL_SERVER; - } - return serverType; - } - - /** - * Read variable from property files if found null try to read from env. - * - * @param key - * @return Value - */ - public static String getConfiguredProperty(String key) { - String value = System.getProperty(key); - - if (value == null) { - value = System.getenv(key); - } - - return value; - } - - /** - * Convenient method for {@link #getConfiguredProperty(String)} - * - * @param key - * @return Value - */ - public static String getConfiguredProperty(String key, String defaultValue) { - String value = getConfiguredProperty(key); - - if (value == null) { - value = defaultValue; - } - - return value; - } - - /** - * - * @param javatype - * @return - */ - public static SqlType find(Class javatype) { - if (null != types) { - types(); - for (SqlType type : types) { - if (type.getType() == javatype) - return type; - } - } - return null; - } - - /** - * - * @param name - * @return - */ - public static SqlType find(String name) { - if (null == types) - types(); - if (null != types) { - for (SqlType type : types) { - if (type.getName().equalsIgnoreCase(name)) - return type; - } - } - return null; - } - - /** - * - * @return - */ - public static ArrayList types() { - if (null == types) { - types = new ArrayList<>(); - - types.add(new SqlInt()); - types.add(new SqlSmallInt()); - types.add(new SqlTinyInt()); - types.add(new SqlBit()); - types.add(new SqlDateTime()); - types.add(new SqlSmallDateTime()); - types.add(new SqlDecimal()); - types.add(new SqlNumeric()); - types.add(new SqlReal()); - types.add(new SqlFloat()); - types.add(new SqlMoney()); - types.add(new SqlSmallMoney()); - types.add(new SqlVarChar()); - types.add(new SqlChar()); - // types.add(new SqlText()); - types.add(new SqlBinary()); - types.add(new SqlVarBinary()); - // types.add(new SqlImage()); - // types.add(new SqlTimestamp()); - - types.add(new SqlNVarChar()); - types.add(new SqlNChar()); - // types.add(new SqlNText()); - // types.add(new SqlGuid()); - - types.add(new SqlBigInt()); - // types.add(new SqlVariant(this)); - - // 9.0 types - types.add(new SqlVarCharMax()); - types.add(new SqlNVarCharMax()); - types.add(new SqlVarBinaryMax()); - // types.add(new SqlXml()); - - // 10.0 types - types.add(new SqlDate()); - types.add(new SqlDateTime2()); - types.add(new SqlTime()); - types.add(new SqlDateTimeOffset()); - } - return types; - } - - /** - * Wrapper Class for BinaryStream - * - */ - public static class DBBinaryStream extends ByteArrayInputStream { - byte[] data; - - // Constructor - public DBBinaryStream(byte[] value) { - super(value); - data = value; - } - - } - - /** - * Wrapper for CharacterStream - * - */ - public static class DBCharacterStream extends CharArrayReader { - String localValue; - - /** - * Constructor - * - * @param value - */ - public DBCharacterStream(String value) { - super(value.toCharArray()); - localValue = value; - } - - } - - /** - * Wrapper for NCharacterStream - */ - class DBNCharacterStream extends DBCharacterStream { - // Constructor - public DBNCharacterStream(String value) { - super(value); - } - } - - /** - * - * @return location of resource file - */ - public static String getCurrentClassPath() { - try { - String className = new Object() {}.getClass().getEnclosingClass().getName(); - String location = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath() - + "/"; - URI uri = new URI(location.toString()); - return uri.getPath(); - } catch (Exception e) { - fail("Failed to get CSV file path. " + e.getMessage()); - } - return null; - } - - /** - * mimic "DROP TABLE IF EXISTS ..." for older versions of SQL Server - */ - public static void dropTableIfExists(String tableName, java.sql.Statement stmt) throws SQLException { - dropObjectIfExists(tableName, "IsTable", stmt); - } - - /** - * mimic "DROP PROCEDURE IF EXISTS ..." for older versions of SQL Server - */ - public static void dropProcedureIfExists(String procName, java.sql.Statement stmt) throws SQLException { - dropObjectIfExists(procName, "IsProcedure", stmt); - } - - public static void dropDatabaseIfExists(String databaseName, java.sql.Statement stmt) throws SQLException { - stmt.executeUpdate("USE MASTER; IF EXISTS(SELECT * from sys.databases WHERE name='" + databaseName - + "') DROP DATABASE [" + databaseName + "]"); - } - - /** - * actually perform the "DROP TABLE / PROCEDURE" - */ - private static void dropObjectIfExists(String objectName, String objectProperty, - java.sql.Statement stmt) throws SQLException { - StringBuilder sb = new StringBuilder(); - if (!objectName.startsWith("[")) { - sb.append("["); - } - sb.append(objectName); - if (!objectName.endsWith("]")) { - sb.append("]"); - } - String bracketedObjectName = sb.toString(); - String sql = String.format("IF EXISTS " + "( " + "SELECT * from sys.objects " - + "WHERE object_id = OBJECT_ID(N'%s') AND OBJECTPROPERTY(object_id, N'%s') = 1 " + ") " + "DROP %s %s ", - bracketedObjectName, objectProperty, "IsProcedure".equals(objectProperty) ? "PROCEDURE" : "TABLE", - bracketedObjectName); - stmt.executeUpdate(sql); - } - - public static boolean parseByte(byte[] expectedData, byte[] retrieved) { - assertTrue(Arrays.equals(expectedData, Arrays.copyOf(retrieved, expectedData.length)), - " unexpected BINARY value, expected"); - for (int i = expectedData.length; i < retrieved.length; i++) { - assertTrue(0 == retrieved[i], "unexpected data BINARY"); - } - return true; - } - - public static boolean isJDBC43OrGreater(Connection connection) throws SQLException { - return getJDBCVersion(connection) >= 4.3F; - } - - public static float getJDBCVersion(Connection connection) throws SQLException { - return Float.valueOf( - connection.getMetaData().getJDBCMajorVersion() + "." + connection.getMetaData().getJDBCMinorVersion()); - } - - public static boolean serverSupportsUTF8(Connection connection) throws SQLException { - try (Statement stmt = connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT name FROM sys.fn_helpcollations() WHERE name LIKE '%UTF8%'");) { - return rs.isBeforeFirst(); - } - } -} diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java index 3a0772c54..b412ca55a 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java @@ -8,8 +8,8 @@ import java.sql.JDBCType; import java.util.concurrent.ThreadLocalRandom; +import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.DBCoercion; -import com.microsoft.sqlserver.testframework.Utils; /* @@ -33,7 +33,7 @@ public SqlChar() { coercions .add(new DBCoercion(String.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.CHAR})); - coercions.add(new DBCoercion(Utils.DBCharacterStream.class, + coercions.add(new DBCoercion(TestUtils.DBCharacterStream.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.STREAM, DBCoercion.CHAR})); diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java index 964c2bc20..3f9383e69 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java @@ -7,9 +7,9 @@ import java.sql.JDBCType; +import com.microsoft.sqlserver.jdbc.TestUtils.DBBinaryStream; +import com.microsoft.sqlserver.jdbc.TestUtils.DBCharacterStream; import com.microsoft.sqlserver.testframework.DBCoercion; -import com.microsoft.sqlserver.testframework.Utils.DBBinaryStream; -import com.microsoft.sqlserver.testframework.Utils.DBCharacterStream; /** From 683740420c1a10d7a6f6a9c1a33df84949c59d77 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Tue, 4 Sep 2018 17:13:26 -0700 Subject: [PATCH 09/15] review update --- .../jdbc/unit/statement/StatementTest.java | 1617 ++++++++--------- 1 file changed, 779 insertions(+), 838 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 5c66a9722..f2d481e25 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 @@ -112,13 +112,14 @@ public void testCancelBeforeExecute() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { stmt.cancel(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); - int numSelectedRows = 0; - while (rs.next()) - ++numSelectedRows; + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + int numSelectedRows = 0; + while (rs.next()) + ++numSelectedRows; - // Wrong number of rows returned - assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); + // Wrong number of rows returned + assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); + } } } @@ -302,215 +303,181 @@ public void run() { @Test public void testCancelBlockedResponse() throws Exception { - Connection conLock = null; - Statement stmtLock = null; - - Connection con = null; - Statement stmt = null; - ResultSet rs = null; Thread oneShotCancel = null; - try { + try (Connection conLock = DriverManager.getConnection(connectionString)) { // Start a transaction on a second connection that locks the last part of the table // and leave it non-responsive for now... - conLock = DriverManager.getConnection(connectionString); conLock.setAutoCommit(false); - stmtLock = conLock.createStatement(); - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); - - con = DriverManager.getConnection(connectionString); - // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options - // are always ON and can NOT be turned OFF. Thus the default transaction isolation level READ_COMMITTED - // always uses snapshot row-versioning in SQL Azure, and the reader transaction will not be blocked if - // it's executing at the default isolation level. - // To allow the blocking behavior for the reader transaction (as required by the test logic), - // we have to set its isolation level to REPEATABLE_READ (or SERIALIZABLE) in SQL Azure. - // - // Reference: http://msdn.microsoft.com/en-us/library/ee336245.aspx#isolevels - if (DBConnection.isSqlAzure(con)) { - con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); - } - - // Try to SELECT the entire table. This should return some rows and then block - // on the locked part of the table until the one shot cancel thread cancels - // statement execution. - // - // Need to use adaptive response buffering when executing the statement. - // Otherwise, we would block in executeQuery()... - stmt = con.createStatement(SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); - rs = stmt.executeQuery("SELECT * FROM " + tableName); + try (Statement stmtLock = conLock.createStatement()) { + stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " + + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + + try (Connection con = DriverManager.getConnection(connectionString)) { + // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options + // are always ON and can NOT be turned OFF. Thus the default transaction isolation level + // READ_COMMITTED + // always uses snapshot row-versioning in SQL Azure, and the reader transaction will not be + // blocked + // if + // it's executing at the default isolation level. + // To allow the blocking behavior for the reader transaction (as required by the test logic), + // we have to set its isolation level to REPEATABLE_READ (or SERIALIZABLE) in SQL Azure. + // + // Reference: http://msdn.microsoft.com/en-us/library/ee336245.aspx#isolevels + if (DBConnection.isSqlAzure(con)) { + con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + } - // Time how long it takes for execution to be cancelled... - long elapsedMillis = -System.currentTimeMillis(); + // Try to SELECT the entire table. This should return some rows and then block + // on the locked part of the table until the one shot cancel thread cancels + // statement execution. + // + // Need to use adaptive response buffering when executing the statement. + // Otherwise, we would block in executeQuery()... + try (Statement stmt = con.createStatement(SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY)) { + ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - // Start up a thread to cancel the SELECT after 3 seconds. - oneShotCancel = new Thread(new OneShotCancel(stmt, 3)); - oneShotCancel.start(); + // Time how long it takes for execution to be cancelled... + long elapsedMillis = -System.currentTimeMillis(); - // Start retrieving rows - int numSelectedRows = 0; + // Start up a thread to cancel the SELECT after 3 seconds. + oneShotCancel = new Thread(new OneShotCancel(stmt, 3)); + oneShotCancel.start(); - try { - while (rs.next()) - ++numSelectedRows; - log.fine("numSelectedRows: " + numSelectedRows); + // Start retrieving rows + int numSelectedRows = 0; - assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertTrue(TestResource.getResource("R_queryCancelled").equalsIgnoreCase(e.getMessage()), - TestResource.getResource("R_unexpectedException")); - } + try { + while (rs.next()) + ++numSelectedRows; + log.fine("numSelectedRows: " + numSelectedRows); - elapsedMillis += System.currentTimeMillis(); + assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertTrue(TestResource.getResource("R_queryCancelled").equalsIgnoreCase( + e.getMessage()), TestResource.getResource("R_unexpectedException")); + } - // We should be able to retrieve no more than the number of rows before the blocked row. - // Note that we may actually get fewer rows than the number of rows before the blocked row - // if SQL Server is a little slow in returning rows to us. - if (numSelectedRows >= NUM_TABLE_ROWS - MIN_TABLE_ROWS) { - assertEquals(NUM_TABLE_ROWS - MIN_TABLE_ROWS, numSelectedRows, - TestResource.getResource("R_valueNotMatch")); - } + elapsedMillis += System.currentTimeMillis(); - // If we were able to iterate through all of the expected - // rows without blocking, then something went wrong with our - // efforts to block execution. - if (elapsedMillis < 2500) { - assertEquals(2500, (int) elapsedMillis, TestResource.getResource("R_executionNotLong")); - } + // We should be able to retrieve no more than the number of rows before the blocked row. + // Note that we may actually get fewer rows than the number of rows before the blocked + // row + // if SQL Server is a little slow in returning rows to us. + if (numSelectedRows >= NUM_TABLE_ROWS - MIN_TABLE_ROWS) { + assertEquals(NUM_TABLE_ROWS - MIN_TABLE_ROWS, numSelectedRows, + TestResource.getResource("R_valueNotMatch")); + } - rs.close(); - rs = null; + // If we were able to iterate through all of the expected + // rows without blocking, then something went wrong with our + // efforts to block execution. + if (elapsedMillis < 2500) { + assertEquals(2500, (int) elapsedMillis, + TestResource.getResource("R_executionNotLong")); + } + } - // Verify the statement & connection are still usable after cancelling - rs = stmt.executeQuery("SELECT 1"); - while (rs.next()); - } finally { - if (null != rs) - try { - rs.close(); - } catch (SQLException e) {} - if (null != stmt) - try { - stmt.close(); - } catch (SQLException e) {} - if (null != con) - try { - con.close(); - } catch (SQLException e) {} - if (null != conLock) - try { - conLock.close(); - } catch (SQLException e) {} + // Verify the statement & connection are still usable after cancelling + try (ResultSet rs = stmt.executeQuery("SELECT 1")) { + while (rs.next()); + } + } + } + } } } @Test public void testCancelBlockedResponsePS() throws Exception { - Connection conLock = null; - Statement stmtLock = null; - - Connection con = null; - PreparedStatement stmt = null; - ResultSet rs = null; Thread oneShotCancel = null; - try { + try (Connection conLock = DriverManager.getConnection(connectionString)) { // Start a transaction on a second connection that locks the last part of the table // and leave it non-responsive for now... - conLock = DriverManager.getConnection(connectionString); conLock.setAutoCommit(false); - stmtLock = conLock.createStatement(); - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); - - con = DriverManager.getConnection(connectionString); - // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options - // are always ON and can NOT be turned OFF. Thus the default transaction isolation level READ_COMMITTED - // always uses snapshot row-versioning in SQL Azure, and the reader transaction will not be blocked if - // it's executing at the default isolation level. - // To allow the blocking behavior for the reader transaction (as required by the test logic), - // we have to set its isolation level to REPEATABLE_READ (or SERIALIZABLE) in SQL Azure. - // - // Reference: http://msdn.microsoft.com/en-us/library/ee336245.aspx#isolevels - if (DBConnection.isSqlAzure(con)) { - con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); - } - - // Try to SELECT the entire table. This should return some rows and then block - // on the locked part of the table until the one shot cancel thread cancels - // statement execution. - // - // Need to use adaptive response buffering when executing the statement. - // Otherwise, we would block in executeQuery()... - stmt = con.prepareStatement("SELECT * FROM " + tableName, - SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); - rs = stmt.executeQuery(); - - // Time how long it takes for execution to be cancelled... - long elapsedMillis = -System.currentTimeMillis(); - - // Start up a thread to cancel the SELECT after 3 seconds. - oneShotCancel = new Thread(new OneShotCancel(stmt, 3)); - oneShotCancel.start(); + try (Statement stmtLock = conLock.createStatement()) { + stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " + + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + + try (Connection con = DriverManager.getConnection(connectionString)) { + // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options + // are always ON and can NOT be turned OFF. Thus the default transaction isolation level + // READ_COMMITTED + // always uses snapshot row-versioning in SQL Azure, and the reader transaction will not be + // blocked if + // it's executing at the default isolation level. + // To allow the blocking behavior for the reader transaction (as required by the test logic), + // we have to set its isolation level to REPEATABLE_READ (or SERIALIZABLE) in SQL Azure. + // + // Reference: http://msdn.microsoft.com/en-us/library/ee336245.aspx#isolevels + if (DBConnection.isSqlAzure(con)) { + con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + } - // Start retrieving rows and see how far we get... - int numSelectedRows = 0; - try { - while (rs.next()) - ++numSelectedRows; + // Try to SELECT the entire table. This should return some rows and then block + // on the locked part of the table until the one shot cancel thread cancels + // statement execution. + // + // Need to use adaptive response buffering when executing the statement. + // Otherwise, we would block in executeQuery()... + try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM " + tableName, + SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { + ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); + try (ResultSet rs = stmt.executeQuery()) { + + // Time how long it takes for execution to be cancelled... + long elapsedMillis = -System.currentTimeMillis(); + + // Start up a thread to cancel the SELECT after 3 seconds. + oneShotCancel = new Thread(new OneShotCancel(stmt, 3)); + oneShotCancel.start(); + + // Start retrieving rows and see how far we get... + int numSelectedRows = 0; + try { + while (rs.next()) + ++numSelectedRows; + + assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertTrue(TestResource.getResource("R_queryCancelled").contains(e.getMessage()), + TestResource.getResource("R_unexpectedException")); + } - assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertTrue(TestResource.getResource("R_queryCancelled").contains(e.getMessage()), - TestResource.getResource("R_unexpectedException")); - } + elapsedMillis += System.currentTimeMillis(); - elapsedMillis += System.currentTimeMillis(); + // We should be able to retrieve no more than the number of rows before the blocked row. + // Note that we may actually get fewer rows than the number of rows before the blocked + // row + // if SQL Server is a little slow in returning rows to us. + if (numSelectedRows >= NUM_TABLE_ROWS - MIN_TABLE_ROWS) { + assertEquals(NUM_TABLE_ROWS - MIN_TABLE_ROWS, numSelectedRows, + TestResource.getResource("R_valueNotMatch")); + } - // We should be able to retrieve no more than the number of rows before the blocked row. - // Note that we may actually get fewer rows than the number of rows before the blocked row - // if SQL Server is a little slow in returning rows to us. - if (numSelectedRows >= NUM_TABLE_ROWS - MIN_TABLE_ROWS) { - assertEquals(NUM_TABLE_ROWS - MIN_TABLE_ROWS, numSelectedRows, - TestResource.getResource("R_valueNotMatch")); - } + // If we were able to iterate through all of the expected + // rows without blocking, then something went wrong with our + // efforts to block execution. + if (elapsedMillis < 2500) { + assertEquals(2500, (int) elapsedMillis, + TestResource.getResource("R_executionNotLong")); + } + } - // If we were able to iterate through all of the expected - // rows without blocking, then something went wrong with our - // efforts to block execution. - if (elapsedMillis < 2500) { - assertEquals(2500, (int) elapsedMillis, TestResource.getResource("R_executionNotLong")); + // Verify the statement & connection are still usable after cancelling + try (ResultSet rs = stmt.executeQuery()) { + rs.next(); + stmt.cancel(); + } + } + } } - - rs.close(); - rs = null; - - // Verify the statement & connection are still usable after cancelling - rs = stmt.executeQuery(); - rs.next(); - stmt.cancel(); - } finally { - if (null != rs) - try { - rs.close(); - } catch (SQLException e) {} - if (null != stmt) - try { - stmt.close(); - } catch (SQLException e) {} - if (null != con) - try { - con.close(); - } catch (SQLException e) {} - if (null != conLock) - try { - conLock.close(); - } catch (SQLException e) {} } } @@ -522,90 +489,83 @@ public void testCancelBlockedResponsePS() throws Exception { */ @Test public void testCancelBlockedCursoredResponse() throws Exception { - Connection conLock = null; - Statement stmtLock = null; - - Connection con = null; - PreparedStatement stmt = null; - Thread oneShotCancel = null; - try { + try (Connection conLock = DriverManager.getConnection(connectionString)) { // Start a transaction on a second connection that locks the last part of the table // and leave it non-responsive for now... - conLock = DriverManager.getConnection(connectionString); conLock.setAutoCommit(false); - stmtLock = conLock.createStatement(); - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); - - con = DriverManager.getConnection(connectionString); - // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options - // are always ON and can NOT be turned OFF. Thus the default transaction isolation level READ_COMMITTED - // always uses snapshot row-versioning in SQL Azure, and the reader transaction will not be blocked if - // it's executing at the default isolation level. - // To allow the blocking behavior for the reader transaction (as required by the test logic), - // we have to set its isolation level to REPEATABLE_READ (or SERIALIZABLE) in SQL Azure. - // - // Reference: http://msdn.microsoft.com/en-us/library/ee336245.aspx#isolevels - if (DBConnection.isSqlAzure(con)) { - con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); - } - - stmt = con.prepareStatement("SELECT * FROM " + tableName, - SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - - // Start up a thread to cancel the following SELECT after 3 seconds of blocking. - oneShotCancel = new Thread(new OneShotCancel(stmt, 3)); - oneShotCancel.start(); - long elapsedMillis = -System.currentTimeMillis(); - - // Try to SELECT the entire table. - ResultSet rs = stmt.executeQuery(); - int numSelectedRows = 0; - - // Verify that we can get the first block of rows. A DYNAMIC cursor won't block - // on the selection until it encounters the table page with the blocked row. - while (numSelectedRows < MIN_TABLE_ROWS && rs.next()) - ++numSelectedRows; - - assertEquals(MIN_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); - - // Now, try to grab the remaining rows from the result set. At some point the call - // to ResultSet.next() should block until the statement is cancelled from the other - // thread. - try { - while (rs.next()) - ++numSelectedRows; + try (Statement stmtLock = conLock.createStatement()) { + stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " + + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + + try (Connection con = DriverManager.getConnection(connectionString)) { + // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options + // are always ON and can NOT be turned OFF. Thus the default transaction isolation level + // READ_COMMITTED + // always uses snapshot row-versioning in SQL Azure, and the reader transaction will not be + // blocked + // if + // it's executing at the default isolation level. + // To allow the blocking behavior for the reader transaction (as required by the test logic), + // we have to set its isolation level to REPEATABLE_READ (or SERIALIZABLE) in SQL Azure. + // + // Reference: http://msdn.microsoft.com/en-us/library/ee336245.aspx#isolevels + if (DBConnection.isSqlAzure(con)) { + con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + } - assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - assertTrue(TestResource.getResource("R_queryCancelled").contains(e.getMessage()), - TestResource.getResource("R_unexpectedException")); - } - elapsedMillis += System.currentTimeMillis(); + try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM " + tableName, + SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { + + // Start up a thread to cancel the following SELECT after 3 seconds of blocking. + oneShotCancel = new Thread(new OneShotCancel(stmt, 3)); + oneShotCancel.start(); + long elapsedMillis = -System.currentTimeMillis(); + + // Try to SELECT the entire table. + try (ResultSet rs = stmt.executeQuery()) { + int numSelectedRows = 0; + + // Verify that we can get the first block of rows. A DYNAMIC cursor won't block + // on the selection until it encounters the table page with the blocked row. + while (numSelectedRows < MIN_TABLE_ROWS && rs.next()) + ++numSelectedRows; + + assertEquals(MIN_TABLE_ROWS, numSelectedRows, + TestResource.getResource("R_valueNotMatch")); + + // Now, try to grab the remaining rows from the result set. At some point the call + // to ResultSet.next() should block until the statement is cancelled from the other + // thread. + try { + while (rs.next()) + ++numSelectedRows; + + assertEquals(false, true, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + assertTrue(TestResource.getResource("R_queryCancelled").contains(e.getMessage()), + TestResource.getResource("R_unexpectedException")); + } + elapsedMillis += System.currentTimeMillis(); - // If we get here to early, then we were able to scan through the rows too fast. - // There's some slop in the elapsed time due to imprecise timer resolution. - if (elapsedMillis < 2500) { - assertEquals(2500, (int) elapsedMillis, TestResource.getResource("R_executionNotLong")); - } + // If we get here to early, then we were able to scan through the rows too fast. + // There's some slop in the elapsed time due to imprecise timer resolution. + if (elapsedMillis < 2500) { + assertEquals(2500, (int) elapsedMillis, + TestResource.getResource("R_executionNotLong")); + } - // Looks like we were canceled. Exception message matched. Time took as long - // as expected. One last check: Make sure we actually get back fewer rows than - // we initially asked for. If any rows beyond the locked row were returned - // then something went wrong. - assertEquals(true, (numSelectedRows <= NUM_TABLE_ROWS - MIN_TABLE_ROWS), - TestResource.getResource("R_valueNotMatch")); - } finally { - if (null != con) - try { - con.close(); - } catch (SQLException e) {} - if (null != conLock) - try { - conLock.close(); - } catch (SQLException e) {} + // Looks like we were canceled. Exception message matched. Time took as long + // as expected. One last check: Make sure we actually get back fewer rows than + // we initially asked for. If any rows beyond the locked row were returned + // then something went wrong. + assertEquals(true, (numSelectedRows <= NUM_TABLE_ROWS - MIN_TABLE_ROWS), + TestResource.getResource("R_valueNotMatch")); + } + } + } + } } } @@ -614,33 +574,28 @@ public void testCancelBlockedCursoredResponse() throws Exception { */ @Test public void testCancelAfterResponse() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - - ResultSet rs; int numSelectedRows; + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + numSelectedRows = 0; + while (rs.next()) + ++numSelectedRows; + } - // Execute a query and consume the entire response - rs = stmt.executeQuery("SELECT * FROM " + tableName); - numSelectedRows = 0; - while (rs.next()) - ++numSelectedRows; - rs.close(); - assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); - - // "Cancel" the executed query - stmt.cancel(); - - // Verify that the query can be re-executed without error - rs = stmt.executeQuery("SELECT * FROM " + tableName); - numSelectedRows = 0; - while (rs.next()) - ++numSelectedRows; - rs.close(); - assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); - - stmt.close(); - con.close(); + assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); + + // "Cancel" the executed query + stmt.cancel(); + + // Verify that the query can be re-executed without error + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + numSelectedRows = 0; + while (rs.next()) + ++numSelectedRows; + } + assertEquals(NUM_TABLE_ROWS, numSelectedRows, TestResource.getResource("R_valueNotMatch")); + } } /** @@ -662,35 +617,35 @@ public void testCancelGetOutParams() throws Exception { stmt.executeUpdate("CREATE PROCEDURE " + procName + " @arg1 CHAR(512) OUTPUT, " + " @arg2 CHAR(512) OUTPUT, " + " @arg3 CHAR(512) OUTPUT " + "AS " + "BEGIN " + " SET @arg1='hi' " + " SET @arg2='there' " + " SET @arg3='!' " + "END"); - CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?, ?)}"); - ((SQLServerStatement) cstmt).setResponseBuffering("adaptive"); - cstmt.registerOutParameter(1, Types.CHAR); - cstmt.registerOutParameter(2, Types.CHAR); - cstmt.registerOutParameter(3, Types.CHAR); - - // Cancel before getting any OUT params - cstmt.execute(); - cstmt.cancel(); - - // Cancel after getting first OUT param - cstmt.execute(); - cstmt.getString(1); - cstmt.cancel(); - - // Cancel after getting last OUT param - cstmt.execute(); - cstmt.getString(3); - cstmt.cancel(); - - // Cancel after getting OUT params out of order - cstmt.execute(); - cstmt.getString(2); - cstmt.getString(1); - cstmt.cancel(); - - // Reexecute to prove CS is still good after last cancel - cstmt.execute(); + try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?, ?)}")) { + ((SQLServerStatement) cstmt).setResponseBuffering("adaptive"); + cstmt.registerOutParameter(1, Types.CHAR); + cstmt.registerOutParameter(2, Types.CHAR); + cstmt.registerOutParameter(3, Types.CHAR); + + // Cancel before getting any OUT params + cstmt.execute(); + cstmt.cancel(); + + // Cancel after getting first OUT param + cstmt.execute(); + cstmt.getString(1); + cstmt.cancel(); + + // Cancel after getting last OUT param + cstmt.execute(); + cstmt.getString(3); + cstmt.cancel(); + // Cancel after getting OUT params out of order + cstmt.execute(); + cstmt.getString(2); + cstmt.getString(1); + cstmt.cancel(); + + // Reexecute to prove CS is still good after last cancel + cstmt.execute(); + } TestUtils.dropProcedureIfExists(procName, stmt); } } @@ -817,7 +772,9 @@ void stop() { } try { - newStmt.close(); + if (null != newStmt) { + newStmt.close(); + } } catch (SQLException e) { log.fine(id + ": close threw: " + e.getMessage()); ++numCloseExceptions; @@ -910,9 +867,7 @@ public void testCloseOnCompletion() throws Exception { } - ResultSet rs; - try { - rs = ps.executeQuery(); + try (ResultSet rs = ps.executeQuery()) { rs.close(); } catch (SQLException e) { log.fine("testIsCloseOnCompletion threw: " + e.getMessage()); @@ -1119,7 +1074,6 @@ public class TCStatementCallable { */ @Test public void testJdbc41CallableStatementMethods() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Prepare database setup try (Connection conn = DriverManager.getConnection(connectionString); @@ -1280,53 +1234,54 @@ public class TCStatementParam { */ @Test public void testStatementOutParamGetsTwice() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - log.fine("testStatementOutParamGetsTwice threw: " + e.getMessage()); - } + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { + log.fine("testStatementOutParamGetsTwice threw: " + e.getMessage()); + } - stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp - + " ( @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) { - rs.close(); - assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); - } else { - assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); - } - - CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); - cstmt.registerOutParameter(1, Types.INTEGER); - cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); - cstmt.registerOutParameter(3, Types.SMALLINT); - cstmt.execute(); - assertEquals(cstmt.getInt(1), 33, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(3), 32, TestResource.getResource("R_valueNotMatch")); - - cstmt.setObject(2, Short.valueOf("34"), Types.SMALLINT); - cstmt.execute(); - assertEquals(cstmt.getInt(1), 35, TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getInt(3), 34, TestResource.getResource("R_valueNotMatch")); - rs = cstmt.getResultSet(); - if (rs != null) { - rs.close(); - assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); - } else { - assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); - } + try (ResultSet rs = stmt.getResultSet()) { + if (rs != null) { + rs.close(); + assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + } else { + assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); + } + } + + try (CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}")) { + cstmt.registerOutParameter(1, Types.INTEGER); + cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); + cstmt.registerOutParameter(3, Types.SMALLINT); + cstmt.execute(); + assertEquals(cstmt.getInt(1), 33, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(3), 32, TestResource.getResource("R_valueNotMatch")); + + cstmt.setObject(2, Short.valueOf("34"), Types.SMALLINT); + cstmt.execute(); + assertEquals(cstmt.getInt(1), 35, TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getInt(3), 34, TestResource.getResource("R_valueNotMatch")); + try (ResultSet rs = cstmt.getResultSet()) { + if (rs != null) { + rs.close(); + assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + } else { + assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); + } + } + } } } @Test public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp @@ -1360,7 +1315,6 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { */ @Test public void testStatementOutParamGetsTwiceInOut() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp @@ -1390,7 +1344,6 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { */ @Test public void testResultSetParams() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { @@ -1406,10 +1359,11 @@ public void testResultSetParams() throws Exception { try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { cstmt.setInt(1, 0); cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); - ResultSet rs = cstmt.executeQuery(); - rs.next(); - assertEquals(rs.getString(2), "hello", TestResource.getResource("R_valueNotMatch")); - assertEquals(cstmt.getString(2), "hi", TestResource.getResource("R_valueNotMatch")); + try (ResultSet rs = cstmt.executeQuery()) { + rs.next(); + assertEquals(rs.getString(2), "hello", TestResource.getResource("R_valueNotMatch")); + assertEquals(cstmt.getString(2), "hi", TestResource.getResource("R_valueNotMatch")); + } } } } @@ -1421,7 +1375,6 @@ public void testResultSetParams() throws Exception { */ @Test public void testResultSetNullParams() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { @@ -1452,7 +1405,6 @@ public void testResultSetNullParams() throws Exception { */ @Test public void testFailedToResumeTransaction() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { @@ -1461,12 +1413,11 @@ public void testFailedToResumeTransaction() throws Exception { stmt.executeUpdate("Insert into " + tableName + " values(1)"); stmt.executeUpdate("Insert into " + tableName + " values(2)"); stmt.executeUpdate("Insert into " + tableName + " values(3)"); - PreparedStatement ps = con - .prepareStatement("BEGIN TRAN " + "Insert into " + tableName + " values(4) " + "ROLLBACK"); - + try (PreparedStatement ps = con + .prepareStatement("BEGIN TRAN " + "Insert into " + tableName + " values(4) " + "ROLLBACK")) {} con.setAutoCommit(false); + try (PreparedStatement ps2 = con.prepareStatement("Insert into " + tableName + " values('a')")) { - try { ps2.execute(); } catch (SQLException e) {} @@ -1483,7 +1434,6 @@ public void testFailedToResumeTransaction() throws Exception { */ @Test public void testResultSetErrors() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { @@ -1513,7 +1463,6 @@ public void testResultSetErrors() throws Exception { @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"); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { @@ -1622,7 +1571,6 @@ public class TCSparseColumnSetAndNBCROW { private final String tableName = AbstractSQLGenerator.escapeIdentifier(temp); private Connection createConnectionAndPopulateData() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); ds.setSelectMethod("direct"); @@ -1659,30 +1607,29 @@ public void terminate() throws Exception { */ @Test public void testNBCROWNullsForLOBs() throws Exception { - - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testNBCROWNullsForLOBs skipped for Yukon"); + try (DBConnection dbconn = new DBConnection(connectionString)) { + if (dbconn.getServerVersion() <= 9.0) { + log.fine("testNBCROWNullsForLOBs skipped for Yukon"); + } } - Connection con = null; - try { - con = createConnectionAndPopulateData(); + try (Connection con = createConnectionAndPopulateData()) { Statement stmt = con.createStatement(); String selectQuery = "SELECT col1_int, col2_varchar, col3_varchar, col4_smallint, col5_xml, col6_nvarcharMax, col7_varcharMax FROM " + tableName; - ResultSet rs = stmt.executeQuery(selectQuery); - rs.next(); + try (ResultSet rs = stmt.executeQuery(selectQuery)) { + rs.next(); - for (int i = 1; i <= 7; i++) { - String value = rs.getString(i); - if (i != 1) { - assertEquals(value, null, "expected null:" + value); + for (int i = 1; i <= 7; i++) { + String value = rs.getString(i); + if (i != 1) { + assertEquals(value, null, "expected null:" + value); + } } } } finally { terminate(); } - } /** @@ -1693,31 +1640,31 @@ public void testNBCROWNullsForLOBs() throws Exception { */ @Test public void testSparseColumnSetValues() throws Exception { - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testSparseColumnSetValues skipped for Yukon"); + try (DBConnection dbconn = new DBConnection(connectionString)) { + if (dbconn.getServerVersion() <= 9.0) { + log.fine("testSparseColumnSetValues skipped for Yukon"); + } } - Connection con = null; - try { - con = createConnectionAndPopulateData(); - Statement stmt = con.createStatement(); + try (Connection con = createConnectionAndPopulateData(); Statement stmt = con.createStatement()) { String selectQuery = "SELECT col1_int, col2_varchar, col3_varchar, col4_smallint, col5_xml, col6_nvarcharMax, col7_varcharMax FROM " + tableName; - ResultSet rs = stmt.executeQuery(selectQuery); - rs.next(); + try (ResultSet rs = stmt.executeQuery(selectQuery)) { + rs.next(); - SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - // Test that isSparseColumnSet returns correct value for various columns - boolean isSparseColumnSet = false; - for (int i = 1; i <= 7; i++) { + // Test that isSparseColumnSet returns correct value for various columns + boolean isSparseColumnSet = false; + for (int i = 1; i <= 7; i++) { - isSparseColumnSet = rsmd.isSparseColumnSet(i); - if (i == 5) { - // this is the only sparse column set - assertEquals(isSparseColumnSet, true, "Incorrect value " + isSparseColumnSet); - } else { - assertEquals(isSparseColumnSet, false, "Incorrect value " + isSparseColumnSet); + isSparseColumnSet = rsmd.isSparseColumnSet(i); + if (i == 5) { + // this is the only sparse column set + assertEquals(isSparseColumnSet, true, "Incorrect value " + isSparseColumnSet); + } else { + assertEquals(isSparseColumnSet, false, "Incorrect value " + isSparseColumnSet); + } } } } finally { @@ -1732,32 +1679,31 @@ public void testSparseColumnSetValues() throws Exception { */ @Test public void testSparseColumnSetIndex() throws Exception { - - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testSparseColumnSetIndex skipped for Yukon"); + try (DBConnection dbconn = new DBConnection(connectionString)) { + if (dbconn.getServerVersion() <= 9.0) { + log.fine("testSparseColumnSetIndex skipped for Yukon"); + } } - Connection con = null; - try { - con = createConnectionAndPopulateData(); - Statement stmt = con.createStatement(); + try (Connection con = createConnectionAndPopulateData(); Statement stmt = con.createStatement()) { String selectQuery = "SELECT col1_int, col2_varchar, col3_varchar, col4_smallint, col5_xml, col6_nvarcharMax, col7_varcharMax FROM " + tableName; - ResultSet rs = stmt.executeQuery(selectQuery); - rs.next(); + try (ResultSet rs = stmt.executeQuery(selectQuery)) { + rs.next(); - SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - try { - // test that an exception is thrown when invalid index(lower limit) is used - rsmd.isSparseColumnSet(0); - assertEquals(true, false, "Using index as 0 should have thrown an exception"); - } catch (ArrayIndexOutOfBoundsException e) {} + SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + try { + // test that an exception is thrown when invalid index(lower limit) is used + rsmd.isSparseColumnSet(0); + assertEquals(true, false, "Using index as 0 should have thrown an exception"); + } catch (ArrayIndexOutOfBoundsException e) {} - try { - // test that an exception is thrown when invalid index(upper limit) is used - rsmd.isSparseColumnSet(8); - assertEquals(true, false, "Using index as 8 should have thrown an exception"); - } catch (ArrayIndexOutOfBoundsException e) {} + try { + // test that an exception is thrown when invalid index(upper limit) is used + rsmd.isSparseColumnSet(8); + assertEquals(true, false, "Using index as 8 should have thrown an exception"); + } catch (ArrayIndexOutOfBoundsException e) {} + } } finally { terminate(); } @@ -1771,33 +1717,33 @@ public void testSparseColumnSetIndex() throws Exception { */ @Test public void testSparseColumnSetForException() throws Exception { - try (DBConnection conn = new DBConnection(connectionString)) { - if (conn.getServerVersion() <= 9.0) { + try (DBConnection dbconn = new DBConnection(connectionString)) { + if (dbconn.getServerVersion() <= 9.0) { log.fine("testSparseColumnSetForException skipped for Yukon"); } } - Connection con = null; - con = createConnectionAndPopulateData(); - Statement stmt = con.createStatement(); - - String selectQuery = "SELECT * FROM " + tableName; - ResultSet rs = stmt.executeQuery(selectQuery); - rs.next(); - SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - rs.close(); - rsmd.isSparseColumnSet(1); - - rs = stmt.executeQuery(selectQuery); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - stmt.close(); - rsmd.isSparseColumnSet(1); - - rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - con.close(); - rsmd.isSparseColumnSet(1); + SQLServerResultSetMetaData rsmd; + try (Connection con = createConnectionAndPopulateData(); Statement stmt = con.createStatement()) { + String selectQuery = "SELECT * FROM " + tableName; + try (ResultSet rs = stmt.executeQuery(selectQuery)) { + rs.next(); + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + rs.close(); + rsmd.isSparseColumnSet(1); + } + try (ResultSet rs = stmt.executeQuery(selectQuery)) { + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + stmt.close(); + rsmd.isSparseColumnSet(1); + } + try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + con.close(); + rsmd.isSparseColumnSet(1); + } + } } /** @@ -1807,18 +1753,17 @@ public void testSparseColumnSetForException() throws Exception { */ @Test public void testNBCRowForAllNulls() throws Exception { - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testNBCRowForAllNulls skipped for Yukon"); + try (DBConnection dbconn = new DBConnection(connectionString)) { + if (dbconn.getServerVersion() <= 9.0) { + log.fine("testNBCRowForAllNulls skipped for Yukon"); + } } - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); ds.setSelectMethod("direct"); - Connection con = null; - try { - con = ds.getConnection(); - Statement stmt = con.createStatement(); + + try (Connection con = ds.getConnection(); Statement stmt = con.createStatement()) { try { TestUtils.dropTableIfExists(tableName, stmt); } catch (SQLException e) {} @@ -1832,15 +1777,15 @@ public void testNBCRowForAllNulls() throws Exception { createTableQuery += ")"; stmt.executeUpdate(createTableQuery); stmt.executeUpdate("INSERT INTO " + tableName + " DEFAULT VALUES"); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + rs.next(); - // test that all columns except the first one are null - for (int i = 2; i <= noOfColumns; i++) { - String value = rs.getString(i); - assertEquals(value, null, "expected null:" + value); + // test that all columns except the first one are null + for (int i = 2; i <= noOfColumns; i++) { + String value = rs.getString(i); + assertEquals(value, null, "expected null:" + value); + } } - } finally { terminate(); } @@ -1853,92 +1798,96 @@ public void testNBCRowForAllNulls() throws Exception { */ @Test public void testNBCROWWithRandomAccess() throws Exception { - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testNBCROWWithRandomAccess skipped for Yukon"); + try (DBConnection dbconn = new DBConnection(connectionString)) { + if (dbconn.getServerVersion() <= 9.0) { + log.fine("testNBCROWWithRandomAccess skipped for Yukon"); + } } - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); ds.setSelectMethod("direct"); - Connection con = null; - try { - con = ds.getConnection(); - Statement stmt = con.createStatement(); - try { - TestUtils.dropTableIfExists(tableName, stmt); - } catch (SQLException e) {} - - // construct a query to create a table with 100 columns - String createTableQuery = "CREATE TABLE " + tableName + "(col1 int PRIMARY KEY IDENTITY(1,1)"; + try (Connection con = ds.getConnection()) { + Random r = new Random(); int noOfColumns = 100; int noOfRows = 10; - for (int i = 2; i <= noOfColumns; i++) { - createTableQuery = createTableQuery + ", col" + i + " int"; - } - createTableQuery += ")"; - stmt.executeUpdate(createTableQuery); + ArrayList nonNullColumns = null; + + try (Statement stmt = con.createStatement()) { + try { + TestUtils.dropTableIfExists(tableName, stmt); + } catch (SQLException e) {} - stmt.executeUpdate("TRUNCATE TABLE " + tableName); + // construct a query to create a table with 100 columns + String createTableQuery = "CREATE TABLE " + tableName + "(col1 int PRIMARY KEY IDENTITY(1,1)"; - Random r = new Random(); - // randomly generate columns whose values would be set to a non null value - ArrayList nonNullColumns = new ArrayList<>(); - nonNullColumns.add(1);// this is always non-null - - // Add approximately 10 non-null columns. The number should be low - // so that we get NBCROW token - for (int i = 0; i < 10; i++) { - int nonNullColumn = (int) (r.nextDouble() * noOfColumns) + 1; - if (!nonNullColumns.contains(nonNullColumn)) { - nonNullColumns.add(nonNullColumn); + for (int i = 2; i <= noOfColumns; i++) { + createTableQuery = createTableQuery + ", col" + i + " int"; } - } + createTableQuery += ")"; + stmt.executeUpdate(createTableQuery); - // construct the insert query - String insertQuery = "INSERT INTO " + tableName + "("; - String values = " VALUES("; - for (int i = 1; i < nonNullColumns.size(); i++) { - insertQuery = insertQuery + "col" + nonNullColumns.get(i); - values += "1"; - if (i == nonNullColumns.size() - 1) { - insertQuery += ")"; - values += ")"; - } else { - insertQuery += ","; - values += ","; + stmt.executeUpdate("TRUNCATE TABLE " + tableName); + + // randomly generate columns whose values would be set to a non null value + nonNullColumns = new ArrayList<>(); + nonNullColumns.add(1);// this is always non-null + + // Add approximately 10 non-null columns. The number should be low + // so that we get NBCROW token + for (int i = 0; i < 10; i++) { + int nonNullColumn = (int) (r.nextDouble() * noOfColumns) + 1; + if (!nonNullColumns.contains(nonNullColumn)) { + nonNullColumns.add(nonNullColumn); + } } - } - insertQuery += values; - - // if there are no non-null columns - if (nonNullColumns.size() == 1) - insertQuery = "INSERT INTO " + tableName + " DEFAULT VALUES"; - - log.fine("INSEER Query:" + insertQuery); - // populate the table by executing the insert query - for (int i = 0; i < noOfRows; i++) { - stmt.executeUpdate(insertQuery); - } - - stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName); - - // Try accessing rows and columns randomly for 10 times - for (int j = 0; j < 10; j++) { - int rowNo = (int) (r.nextDouble() * noOfRows) + 1; - log.fine("Moving to row no:" + rowNo); - rs.absolute(rowNo);// move to a row - // With in a row try accessing columns randomly 10 times - for (int k = 1; k < 10; k++) { - int columnNo = (int) (r.nextDouble() * noOfColumns) + 1; - log.fine("Moving to column no:" + columnNo); - String value = rs.getString(columnNo);// get a particular column value - if (nonNullColumns.contains(columnNo)) { - assertTrue(value != null, "value should not be null"); + + // construct the insert query + String insertQuery = "INSERT INTO " + tableName + "("; + String values = " VALUES("; + for (int i = 1; i < nonNullColumns.size(); i++) { + insertQuery = insertQuery + "col" + nonNullColumns.get(i); + values += "1"; + if (i == nonNullColumns.size() - 1) { + insertQuery += ")"; + values += ")"; } else { - assertTrue(value == null, "value should be null:" + value); + insertQuery += ","; + values += ","; + } + } + insertQuery += values; + + // if there are no non-null columns + if (nonNullColumns.size() == 1) + insertQuery = "INSERT INTO " + tableName + " DEFAULT VALUES"; + + log.fine("INSEER Query:" + insertQuery); + // populate the table by executing the insert query + for (int i = 0; i < noOfRows; i++) { + stmt.executeUpdate(insertQuery); + } + } + + try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + // Try accessing rows and columns randomly for 10 times + for (int j = 0; j < 10; j++) { + int rowNo = (int) (r.nextDouble() * noOfRows) + 1; + log.fine("Moving to row no:" + rowNo); + rs.absolute(rowNo);// move to a row + // With in a row try accessing columns randomly 10 times + for (int k = 1; k < 10; k++) { + int columnNo = (int) (r.nextDouble() * noOfColumns) + 1; + log.fine("Moving to column no:" + columnNo); + String value = rs.getString(columnNo);// get a particular column value + if (nonNullColumns.contains(columnNo)) { + assertTrue(value != null, "value should not be null"); + } else { + assertTrue(value == null, "value should be null:" + value); + } } } } @@ -1953,27 +1902,24 @@ public void testNBCROWWithRandomAccess() throws Exception { public class TCStatementIsClosed { @Test public void testActiveStatement() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - SQLServerStatement stmt = (SQLServerStatement) conn.createStatement(); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { + log.fine("testCloseOnCompletion threw: " + e.getMessage()); + } - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - log.fine("testCloseOnCompletion threw: " + e.getMessage()); - } + try { + assertEquals(stmt.isClosed(), false, "Wrong return value from Statement.isClosed"); + } catch (UnsupportedOperationException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + } - try { - assertEquals(stmt.isClosed(), false, "Wrong return value from Statement.isClosed"); - } catch (UnsupportedOperationException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); } - - assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); - stmt.close(); - conn.close(); } /** @@ -1983,19 +1929,16 @@ public void testActiveStatement() throws Exception { */ @Test public void testClosedStatement() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - - SQLServerStatement stmt = (SQLServerStatement) conn.createStatement(); - stmt.close(); + try (Connection conn = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + stmt.close(); - try { - assertEquals(stmt.isClosed(), true, "Wrong return value from Statement.isClosed"); - } catch (UnsupportedOperationException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + try { + assertEquals(stmt.isClosed(), true, "Wrong return value from Statement.isClosed"); + } catch (UnsupportedOperationException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + } } - - conn.close(); } /** @@ -2005,16 +1948,15 @@ public void testClosedStatement() throws Exception { */ @Test public void testClosedConnection() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - - SQLServerStatement stmt = (SQLServerStatement) conn.createStatement(); - conn.close(); + try (Connection conn = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + conn.close(); - try { - assertEquals(stmt.isClosed(), true, "Wrong return value from Statement.isClosed"); - } catch (UnsupportedOperationException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + try { + assertEquals(stmt.isClosed(), true, "Wrong return value from Statement.isClosed"); + } catch (UnsupportedOperationException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + } } } } @@ -2028,30 +1970,28 @@ public class TCResultSetIsClosed { */ @Test public void testActiveResultSet() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { - Statement stmt = conn.createStatement(); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException")); + } - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - throw new SQLException(TestResource.getResource("R_unexpectedException")); - } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1")) { - SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1"); + try { + assertEquals(rs.isClosed(), false, "Wrong return value from ResultSet.isClosed"); + } catch (UnsupportedOperationException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + } - try { - assertEquals(rs.isClosed(), false, "Wrong return value from ResultSet.isClosed"); - } catch (UnsupportedOperationException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + rs.close(); + } + assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); } - - rs.close(); - assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); - - conn.close(); } /** @@ -2061,28 +2001,27 @@ public void testActiveResultSet() throws Exception { */ @Test public void testClosedResultSet() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - - Statement stmt = conn.createStatement(); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - throw new SQLException(TestResource.getResource("R_unexpectedException")); - } + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException")); + } - SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1"); - rs.close(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1")) { + rs.close(); - try { - assertEquals(rs.isClosed(), true, "Wrong return value from ResultSet.isClosed"); - } catch (UnsupportedOperationException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + try { + assertEquals(rs.isClosed(), true, "Wrong return value from ResultSet.isClosed"); + } catch (UnsupportedOperationException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + } + } + assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); } - assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); - conn.close(); } /** @@ -2092,21 +2031,19 @@ public void testClosedResultSet() throws Exception { */ @Test public void testClosedStatement() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - - Statement stmt = conn.createStatement(); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { - SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1"); - stmt.close(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1")) { + stmt.close(); - try { - assertEquals(rs.isClosed(), true, "Wrong return value from ResultSet.isClosed"); - } catch (UnsupportedOperationException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + try { + assertEquals(rs.isClosed(), true, "Wrong return value from ResultSet.isClosed"); + } catch (UnsupportedOperationException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + } + } } - - conn.close(); } /** @@ -2116,18 +2053,18 @@ public void testClosedStatement() throws Exception { */ @Test public void testClosedConnection() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection conn = DriverManager.getConnection(connectionString); - - Statement stmt = conn.createStatement(); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { - SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1"); - conn.close(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1")) { + conn.close(); - try { - assertEquals(rs.isClosed(), true, "Wrong return value from ResultSet.isClosed"); - } catch (UnsupportedOperationException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + try { + assertEquals(rs.isClosed(), true, "Wrong return value from ResultSet.isClosed"); + } catch (UnsupportedOperationException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedException"), e.getMessage()); + } + } } } } @@ -2143,36 +2080,36 @@ public class TCUpdateCountWithTriggers { @BeforeEach public void setup() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - con.setAutoCommit(false); - Statement stmt = con.createStatement(); + try (Connection con = DriverManager.getConnection(connectionString)) { + con.setAutoCommit(false); + try (Statement stmt = con.createStatement()) { - try { - stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName - + "') drop trigger " + triggerName); - } catch (SQLException e) { - throw new 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 + ")"); + try { + stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + + "') drop trigger " + triggerName); + } catch (SQLException e) { + throw new 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 + ")"); - stmt.executeUpdate( - "CREATE TABLE " + table2Name + " (NAME VARCHAR(100), col2 int identity(1,1) primary key)"); - stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('BLAH')"); - stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('FNORD')"); - stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('EEEP')"); + stmt.executeUpdate( + "CREATE TABLE " + table2Name + " (NAME VARCHAR(100), col2 int identity(1,1) primary key)"); + stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('BLAH')"); + stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('FNORD')"); + stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('EEEP')"); - stmt.executeUpdate("Create Procedure " + sprocName + " AS " + "Begin " + " Update " + table2Name + " SET " - + " NAME = 'Update' Where NAME = 'TEST' " + "Return 0 " + "End"); + stmt.executeUpdate("Create Procedure " + sprocName + " AS " + "Begin " + " Update " + table2Name + + " SET " + " NAME = 'Update' Where NAME = 'TEST' " + "Return 0 " + "End"); - stmt.executeUpdate("CREATE Trigger " + triggerName + " ON " + tableName + " FOR DELETE AS " + "Begin " - + "Declare @l_retstat Integer " + "Execute @l_retstat = " + sprocName + " " - + "If (@l_retstat <> 0) " + "Begin " + " Rollback Transaction " + "End " + "End"); + stmt.executeUpdate("CREATE Trigger " + triggerName + " ON " + tableName + " FOR DELETE AS " + + "Begin " + "Declare @l_retstat Integer " + "Execute @l_retstat = " + sprocName + " " + + "If (@l_retstat <> 0) " + "Begin " + " Rollback Transaction " + "End " + "End"); - stmt.close(); - con.commit(); - con.close(); + } + con.commit(); + } } /** @@ -2183,16 +2120,15 @@ public void setup() throws Exception { @Test public void testLastUpdateCountTrue() throws Exception { - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); - PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?"); - ps.setInt(1, 1); - int updateCount = ps.executeUpdate(); - ps.close(); - con.close(); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); + PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?")) { + ps.setInt(1, 1); + int updateCount = ps.executeUpdate(); - // updateCount should be from the DELETE, - // which should be 1, since there is onw row with the specified column value (1). - assertEquals(updateCount, 1, "Wrong update count"); + // updateCount should be from the DELETE, + // which should be 1, since there is onw row with the specified column value (1). + assertEquals(updateCount, 1, "Wrong update count"); + } } /** @@ -2203,16 +2139,15 @@ public void testLastUpdateCountTrue() throws Exception { @Test public void testLastUpdateCountFalse() throws Exception { - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=false"); - PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?"); - ps.setInt(1, 1); - int updateCount = ps.executeUpdate(); - ps.close(); - con.close(); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=false"); + PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?")) { + ps.setInt(1, 1); + int updateCount = ps.executeUpdate(); - // updateCount should be from the UDPATE in the trigger procedure, - // which should have affected 0 rows since no row satisfies the WHERE clause. - assertEquals(updateCount, 0, "Wrong update count"); + // updateCount should be from the UDPATE in the trigger procedure, + // which should have affected 0 rows since no row satisfies the WHERE clause. + assertEquals(updateCount, 0, "Wrong update count"); + } } /** @@ -2223,17 +2158,17 @@ public void testLastUpdateCountFalse() throws Exception { @Test public void testPreparedStatementInsertExecInsert() throws Exception { - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); - PreparedStatement ps = con.prepareStatement("INSERT INTO " + tableName + " (col1) VALUES (" + (NUM_ROWS + 1) - + "); " + "EXEC " + sprocName + "; " + "UPDATE " + table2Name + " SET NAME = 'FISH'"); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); + PreparedStatement ps = con + .prepareStatement("INSERT INTO " + tableName + " (col1) VALUES (" + (NUM_ROWS + 1) + "); " + + "EXEC " + sprocName + "; " + "UPDATE " + table2Name + " SET NAME = 'FISH'")) { - int updateCount = ps.executeUpdate(); - ps.close(); - con.close(); + int updateCount = ps.executeUpdate(); - // updateCount should be from the UPDATE, - // which should have affected all 3 rows in table2Name. - assertEquals(updateCount, 3, "Wrong update count"); + // updateCount should be from the UPDATE, + // which should have affected all 3 rows in table2Name. + assertEquals(updateCount, 3, "Wrong update count"); + } } /** @@ -2244,16 +2179,15 @@ public void testPreparedStatementInsertExecInsert() throws Exception { @Test public void testStatementInsertExecInsert() throws Exception { - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); - int updateCount = con.createStatement() - .executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + (NUM_ROWS + 1) + "); " + "EXEC " - + sprocName + "; " + "UPDATE " + table2Name + " SET NAME = 'FISH'"); - - con.close(); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); + Statement stmt = con.createStatement()) { + int updateCount = stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + (NUM_ROWS + 1) + + "); " + "EXEC " + sprocName + "; " + "UPDATE " + table2Name + " SET NAME = 'FISH'"); - // updateCount should be from the INSERT, - // which should have affected 1 (new) row in tableName. - assertEquals(updateCount, 1, "Wrong update count"); + // updateCount should be from the INSERT, + // which should have affected 1 (new) row in tableName. + assertEquals(updateCount, 1, "Wrong update count"); + } } @AfterEach @@ -2281,37 +2215,41 @@ public class TCUpdateCountAfterRaiseError { @BeforeEach public void setup() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - con.setAutoCommit(false); - Statement stmt = con.createStatement(); + try (Connection con = DriverManager.getConnection(connectionString)) { + con.setAutoCommit(false); + try (Statement stmt = con.createStatement()) { - try { - stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName - + "') drop trigger " + triggerName); - } catch (SQLException e) { - System.out.println(e.toString()); - } - 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 + ")"); - - // Skip adding message for 50001 if the target server is SQL Azure, because SQL Azure does not support - // sp_addmessage. - Connection dbConn = DriverManager.getConnection(connectionString); - if (DBConnection.isSqlAzure(dbConn)) { - log.fine("Because SQL Azure does not support sp_addmessage, 'EXEC sp_addmessage ...' is skipped."); - } else { - try { - stmt.executeUpdate("EXEC sp_addmessage @msgnum=50001, @severity=11, @msgtext='MyError'"); - } catch (SQLException e) {} - } - dbConn.close(); + try { + stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + + "') drop trigger " + triggerName); + } catch (SQLException e) { + System.out.println(e.toString()); + } + 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 + ")"); + + // Skip adding message for 50001 if the target server is SQL Azure, because SQL Azure does not + // support + // sp_addmessage. + try (Connection dbConn = DriverManager.getConnection(connectionString)) { + if (DBConnection.isSqlAzure(dbConn)) { + log.fine( + "Because SQL Azure does not support sp_addmessage, 'EXEC sp_addmessage ...' is skipped."); + } else { + try { + stmt.executeUpdate( + "EXEC sp_addmessage @msgnum=50001, @severity=11, @msgtext='MyError'"); + } catch (SQLException e) {} + } + } - stmt.executeUpdate("CREATE TRIGGER " + triggerName + " ON " + tableName - + " FOR INSERT AS BEGIN DELETE FROM " + tableName + " WHERE col1 = 1 RAISERROR(50001, 17, 1) END"); - stmt.close(); - con.commit(); - con.close(); + stmt.executeUpdate( + "CREATE TRIGGER " + triggerName + " ON " + tableName + " FOR INSERT AS BEGIN DELETE FROM " + + tableName + " WHERE col1 = 1 RAISERROR(50001, 17, 1) END"); + } + con.commit(); + } } /** @@ -2322,50 +2260,50 @@ public void setup() throws Exception { @Test public void testUpdateCountAfterRaiseError() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - PreparedStatement pstmt = con.prepareStatement("UPDATE " + tableName - + " SET col1 = 5 WHERE col1 = 2 RAISERROR(50001, 17, 1) SELECT * FROM " + tableName); + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt = con.prepareStatement("UPDATE " + tableName + + " SET col1 = 5 WHERE col1 = 2 RAISERROR(50001, 17, 1) SELECT * FROM " + tableName)) { - // enable isCloseOnCompletion - try { - pstmt.closeOnCompletion(); - } catch (Exception e) { - throw new SQLException(TestResource.getResource("R_unexpectedException")); - } + // enable isCloseOnCompletion + try { + pstmt.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException")); + } + + boolean result = pstmt.execute(); - boolean result = pstmt.execute(); + assertEquals(result, false, "First result: should have been an update count"); + assertEquals(pstmt.getUpdateCount(), 1, "First result: Unexpected number of rows affected by UPDATE"); - assertEquals(result, false, "First result: should have been an update count"); - assertEquals(pstmt.getUpdateCount(), 1, "First result: Unexpected number of rows affected by UPDATE"); + try { + result = pstmt.getMoreResults(); + assertEquals(true, false, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + String expectedMessage; + // SQL Azure does not support sp_addmessage, so the user-defined message cannot be added. + if (DBConnection.isSqlAzure(con)) // SQL Azure + { + expectedMessage = errorMessage50001InSqlAzure; + } else // SQL Server + { + expectedMessage = "MyError"; + } + assertEquals(e.getMessage(), expectedMessage, + "Second result: Unexpected error message from RAISERROR"); + } - try { result = pstmt.getMoreResults(); - assertEquals(true, false, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - String expectedMessage; - // SQL Azure does not support sp_addmessage, so the user-defined message cannot be added. - if (DBConnection.isSqlAzure(con)) // SQL Azure - { - expectedMessage = errorMessage50001InSqlAzure; - } else // SQL Server - { - expectedMessage = "MyError"; - } - assertEquals(e.getMessage(), expectedMessage, "Second result: Unexpected error message from RAISERROR"); - } - - result = pstmt.getMoreResults(); - assertEquals(result, true, "Third result: wrong result type; ResultSet expected"); - assertEquals(pstmt.getUpdateCount(), -1, "Third result: wrong update count"); - ResultSet rs = pstmt.getResultSet(); - int rowCount = 0; - while (rs.next()) - ++rowCount; - assertEquals(rowCount, NUM_ROWS, "Third result: wrong number of rows returned"); - - rs.close(); - assertEquals(pstmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); - con.close(); + assertEquals(result, true, "Third result: wrong result type; ResultSet expected"); + assertEquals(pstmt.getUpdateCount(), -1, "Third result: wrong update count"); + try (ResultSet rs = pstmt.getResultSet()) { + int rowCount = 0; + while (rs.next()) + ++rowCount; + assertEquals(rowCount, NUM_ROWS, "Third result: wrong number of rows returned"); + } + assertEquals(pstmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); + } } /** @@ -2376,44 +2314,43 @@ public void testUpdateCountAfterRaiseError() throws Exception { @Test public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exception { - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = false"); - PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)"); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = false"); + PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)")) { - int updateCount = pstmt.executeUpdate(); - assertEquals(updateCount, 1, "First result: should have been 1 row deleted"); - assertEquals(pstmt.getUpdateCount(), 1, "First result: Wrong return from getUpdateCount"); + int updateCount = pstmt.executeUpdate(); + assertEquals(updateCount, 1, "First result: should have been 1 row deleted"); + assertEquals(pstmt.getUpdateCount(), 1, "First result: Wrong return from getUpdateCount"); - boolean result; + boolean result; + + try { + result = pstmt.getMoreResults(); + assertEquals(true, false, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + String expectedMessage; + // SQL Azure does not support sp_addmessage, so the user-defined message cannot be added. + if (DBConnection.isSqlAzure(con)) // SQL Azure + { + expectedMessage = errorMessage50001InSqlAzure; + } else // SQL Server + { + expectedMessage = "MyError"; + } + assertEquals(e.getMessage(), expectedMessage, + "Second result: Unexpected error message from RAISERROR"); + } - try { result = pstmt.getMoreResults(); - assertEquals(true, false, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - String expectedMessage; - // SQL Azure does not support sp_addmessage, so the user-defined message cannot be added. - if (DBConnection.isSqlAzure(con)) // SQL Azure - { - expectedMessage = errorMessage50001InSqlAzure; - } else // SQL Server - { - expectedMessage = "MyError"; - } - assertEquals(e.getMessage(), expectedMessage, "Second result: Unexpected error message from RAISERROR"); - } - - result = pstmt.getMoreResults(); - assertEquals(result, false, "Third result: wrong result type; update count expected"); - assertEquals(pstmt.getUpdateCount(), 1, "Third result: wrong number of rows inserted"); - ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); - int rowCount = 0; - while (rs.next()) - ++rowCount; - assertEquals(rowCount, NUM_ROWS, "Wrong number of rows in table"); - assertEquals(pstmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); - rs.close(); - - pstmt.close(); - con.close(); + assertEquals(result, false, "Third result: wrong result type; update count expected"); + assertEquals(pstmt.getUpdateCount(), 1, "Third result: wrong number of rows inserted"); + try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + int rowCount = 0; + while (rs.next()) + ++rowCount; + assertEquals(rowCount, NUM_ROWS, "Wrong number of rows in table"); + assertEquals(pstmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); + } + } } /** @@ -2424,39 +2361,43 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exce @Test public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Exception { - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); - PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)"); - - try { - pstmt.executeUpdate(); - assertEquals(true, false, TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (SQLException e) { - String expectedMessage; - // SQL Azure does not support sp_addmessage, so the user-defined message cannot be added. - if (DBConnection.isSqlAzure(con)) // SQL Azure - { - expectedMessage = errorMessage50001InSqlAzure; - } else // SQL Server - { - expectedMessage = "MyError"; - } - assertEquals(e.getMessage(), expectedMessage, "Second result: Unexpected error message from RAISERROR"); - } - assertEquals(pstmt.getResultSet(), null, "First result: Unexpected update count"); - assertEquals(pstmt.getUpdateCount(), -1, "First result: Unexpected update count"); - - boolean result = pstmt.getMoreResults(); - assertEquals(result, false, "Second result: wrong result type; update count expected"); - assertEquals(pstmt.getUpdateCount(), 1, "Second result: wrong number of rows inserted"); - ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); - int rowCount = 0; - while (rs.next()) - ++rowCount; - assertEquals(rowCount, NUM_ROWS, "Wrong number of rows in table"); - - rs.close(); - pstmt.close(); - con.close(); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); + PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)")) { + + try { + pstmt.executeUpdate(); + assertEquals(true, false, TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (SQLException e) { + String expectedMessage; + // SQL Azure does not support sp_addmessage, so the user-defined message cannot be added. + if (DBConnection.isSqlAzure(con)) // SQL Azure + { + expectedMessage = errorMessage50001InSqlAzure; + } else // SQL Server + { + expectedMessage = "MyError"; + } + assertEquals(e.getMessage(), expectedMessage, + "Second result: Unexpected error message from RAISERROR"); + } + + try (ResultSet rs = pstmt.getResultSet()) { + assertEquals(rs, null, "First result: Unexpected update count"); + + assertEquals(pstmt.getUpdateCount(), -1, "First result: Unexpected update count"); + + boolean result = pstmt.getMoreResults(); + assertEquals(result, false, "Second result: wrong result type; update count expected"); + assertEquals(pstmt.getUpdateCount(), 1, "Second result: wrong number of rows inserted"); + } + + try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + int rowCount = 0; + while (rs.next()) + ++rowCount; + assertEquals(rowCount, NUM_ROWS, "Wrong number of rows in table"); + } + } } @AfterEach @@ -2481,24 +2422,24 @@ public class TCNocount { @BeforeEach public void setup() throws Exception { - Connection con = DriverManager.getConnection(connectionString); - con.setAutoCommit(false); - Statement stmt = con.createStatement(); + try (Connection con = DriverManager.getConnection(connectionString)) { + con.setAutoCommit(false); + try (Statement stmt = con.createStatement()) { - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } catch (Exception e) { - throw new SQLException(TestResource.getResource("R_unexpectedException"), 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 + ")"); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } catch (Exception e) { + throw new SQLException(TestResource.getResource("R_unexpectedException"), 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 + ")"); - assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); - stmt.close(); - con.commit(); - con.close(); + assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); + } + con.commit(); + } } /** @@ -2517,9 +2458,9 @@ public void testNoCountWithExecute() throws Exception { assertEquals(true, isResultSet, "execute() said first result was an update count"); - ResultSet rs = stmt.getResultSet(); - while (rs.next()); - rs.close(); + try (ResultSet rs = stmt.getResultSet()) { + while (rs.next()); + } boolean moreResults = stmt.getMoreResults(); assertEquals(false, moreResults, "next result is a ResultSet?"); From 6b43e4c7abc5ebf387d9ae0228ce065b3aec3caa Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Wed, 12 Sep 2018 16:59:55 -0700 Subject: [PATCH 10/15] more review changes --- .../sqlserver/jdbc/TestResource.java | 2 +- .../microsoft/sqlserver/jdbc/TestUtils.java | 7 +++- .../jdbc/bulkCopy/BulkCopyConnectionTest.java | 4 +- .../bulkCopy/BulkCopyResultSetCursorTest.java | 37 +++++++++++++------ 4 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java index a3b875798..f8b6279ed 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java @@ -42,7 +42,7 @@ protected Object[][] getContents() { {"R_errorMessage", " Error message: "}, {"R_createDropViewFailed", "Create/drop view with preparedStatement failed!"}, {"R_createDropSchemaFailed", "Create/drop schema with preparedStatement failed!"}, - {"R_createDropTableFailed", "Create/drop table with preparedStatement failed!"}, + {"R_createDropTableFailed", "Create/drop table failed!"}, {"R_createDropAlterTableFailed", "Create/drop/alter table with preparedStatement failed!"}, {"R_grantFailed", "grant table with preparedStatement failed!"}, {"R_connectionIsClosed", "The connection is closed."}, diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java index c1e39eedb..5cc92dfb8 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java @@ -306,7 +306,12 @@ private static void dropObjectIfExists(String objectName, String objectProperty, + "WHERE object_id = OBJECT_ID(N'%s') AND OBJECTPROPERTY(object_id, N'%s') = 1 " + ") " + "DROP %s %s ", bracketedObjectName, objectProperty, "IsProcedure".equals(objectProperty) ? "PROCEDURE" : "TABLE", bracketedObjectName); - stmt.executeUpdate(sql); + try { + stmt.executeUpdate(sql); + } catch (SQLException e) { + fail(TestResource.getResource("R_createDropTableFailed") + TestResource.getResource("R_errorMessage") + + e.getMessage()); + } } public static boolean parseByte(byte[] expectedData, byte[] retrieved) { 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 1863bd639..bc6edd757 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java @@ -130,10 +130,10 @@ public void execute() throws SQLException { } /** - * BulkCopy:test null connenction string + * BulkCopy:test null connection string */ @Test - @DisplayName("BulkCopy:test null connenction string") + @DisplayName("BulkCopy:test null connection string") public void testInvalidConnection4() { assertThrows(SQLException.class, new org.junit.jupiter.api.function.Executable() { @Override 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 4d9b7f3e0..113955d19 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -22,6 +22,7 @@ import org.junit.runner.RunWith; import org.junit.jupiter.api.AfterAll; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestUtils; @@ -42,8 +43,8 @@ public class BulkCopyResultSetCursorTest extends AbstractTest { static String[] expectedTimestampStrings = {"2015-06-03 13:35:33.4610000", "2442-09-19 01:59:43.9990000", "2017-04-02 08:58:53.0000000"}; - private static String srcTable = "BulkCopyResultSetCursorTest_SourceTable"; - private static String desTable = "BulkCopyResultSetCursorTest_DestinationTable"; + private static String srcTable = null; + private static String desTable = null; /** * Test a previous failure when using server cursor and using the same connection to create Bulk Copy and result @@ -66,8 +67,8 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro createTables(stmt); populateSourceTable(); - try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency) - .executeQuery("select * from " + srcTable); + try (Statement stmt2 = conn.createStatement(resultSetType, resultSetConcurrency); + ResultSet rs = stmt2.executeQuery("select * from " + srcTable); SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { bulkCopy.setDestinationTableName(desTable); bulkCopy.writeToServer(rs); @@ -93,8 +94,9 @@ public void testSelectMethodSetToCursor() throws SQLException { createTables(stmt); populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + try (ResultSet rs = stmt.executeQuery("select * from " + srcTable); SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); bulkCopy.writeToServer(rs); @@ -116,8 +118,8 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { createTables(stmt); populateSourceTable(); - try (ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) - .executeQuery("select * from " + srcTable)) { + try (Statement stmt1 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + ResultSet rs = stmt1.executeQuery("select * from " + srcTable)) { try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { bulkCopy.setDestinationTableName(desTable); bulkCopy.writeToServer(rs); @@ -150,8 +152,8 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { } verifyDestinationTableData(expectedBigDecimals.length * 4); } - try (ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) - .executeQuery("select * from " + srcTable); + try (Statement stmt2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, + ResultSet.CONCUR_UPDATABLE); ResultSet rs2 = stmt2.executeQuery("select * from " + srcTable); SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn)) { bulkCopy3.setDestinationTableName(desTable); bulkCopy3.writeToServer(rs2); @@ -202,15 +204,26 @@ private static void populateSourceTable() throws SQLException { } private static void dropTables(Statement stmt) throws SQLException { - TestUtils.dropTableIfExists(srcTable, stmt); - TestUtils.dropTableIfExists(desTable, stmt); + if (null != srcTable) { + TestUtils.dropTableIfExists(srcTable, stmt); + } + if (null != desTable) { + TestUtils.dropTableIfExists(desTable, stmt); + } } private static void createTables(Statement stmt) throws SQLException { + + if (null == srcTable) { + srcTable = "[BulkCopyResultSetCursorTest_Source_" + RandomUtil.getIdentifier("table") + "]"; + } + if (null == desTable) { + desTable = "[BulkCopyResultSetCursorTest_Destination_" + RandomUtil.getIdentifier("table") + "]"; + } + 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); From f5a97de3bf5bb724d78e167d1d309cb70d61adeb Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Fri, 14 Sep 2018 16:38:30 -0700 Subject: [PATCH 11/15] more try-with-resources changes --- .../sqlserver/jdbc/ComparisonUtil.java | 84 +- .../jdbc/bulkCopy/BulkCopyAllTypes.java | 9 +- .../jdbc/bulkCopy/BulkCopyTestUtil.java | 3 - .../microsoft/sqlserver/jdbc/bvt/bvtTest.java | 1 - .../CallableStatementTest.java | 37 +- .../jdbc/connection/ConnectionDriverTest.java | 183 ++-- .../jdbc/connection/PoolingTest.java | 19 +- .../RequestBoundaryMethodsTest.java | 118 ++- .../jdbc/connection/TimeoutTest.java | 60 +- .../datatypes/BulkCopyWithSqlVariantTest.java | 872 ++++++++++-------- .../jdbc/datatypes/DateAndTimeTypeTest.java | 217 ++--- .../SQLServerSpatialDatatypeTest.java | 747 ++++++++------- .../jdbc/datatypes/TVPWithSqlVariantTest.java | 250 +++-- .../jdbc/exception/ExceptionTest.java | 44 +- .../preparedStatement/RegressionTest.java | 8 +- .../jdbc/tvp/TVPResultSetCursorTest.java | 363 ++++---- .../sqlserver/jdbc/tvp/TVPTypesTest.java | 200 ++-- .../sqlserver/jdbc/unit/UTF8SupportTest.java | 20 +- .../unit/statement/BatchExecutionTest.java | 5 +- .../jdbc/unit/statement/PoolableTest.java | 63 +- .../unit/statement/PreparedStatementTest.java | 4 +- .../jdbc/unit/statement/WrapperTest.java | 149 ++- 22 files changed, 1772 insertions(+), 1684 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java b/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java index 4f0f266e7..e1f6818e8 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java @@ -20,6 +20,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerResultSetMetaData; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBTable; @@ -36,49 +37,52 @@ public class ComparisonUtil { */ public static void compareSrcTableAndDestTableIgnoreRowOrder(DBConnection con, DBTable srcTable, DBTable destTable) throws SQLException { - DBResultSet srcResultSetCount = con.createStatement() - .executeQuery("SELECT COUNT(*) FROM " + srcTable.getEscapedTableName() + ";"); - DBResultSet dstResultSetCount = con.createStatement() - .executeQuery("SELECT COUNT(*) FROM " + destTable.getEscapedTableName() + ";"); - srcResultSetCount.next(); - dstResultSetCount.next(); - int srcRows = srcResultSetCount.getInt(1); - int destRows = dstResultSetCount.getInt(1); - - if (srcRows != destRows) { - fail("Souce table and Destination table have different number of rows."); - } + try (DBStatement stmt = con.createStatement(); + DBResultSet srcResultSetCount = stmt + .executeQuery("SELECT COUNT(*) FROM " + srcTable.getEscapedTableName() + ";"); + DBResultSet dstResultSetCount = stmt + .executeQuery("SELECT COUNT(*) FROM " + destTable.getEscapedTableName() + ";")) { + srcResultSetCount.next(); + dstResultSetCount.next(); + int srcRows = srcResultSetCount.getInt(1); + int destRows = dstResultSetCount.getInt(1); + + if (srcRows != destRows) { + fail("Souce table and Destination table have different number of rows."); + } - if (srcTable.getColumns().size() != destTable.getColumns().size()) { - fail("Souce table and Destination table have different number of columns."); - } + if (srcTable.getColumns().size() != destTable.getColumns().size()) { + fail("Souce table and Destination table have different number of columns."); + } - DBResultSet srcResultSet = con.createStatement().executeQuery( - "SELECT * FROM " + srcTable.getEscapedTableName() + " ORDER BY [" + srcTable.getColumnName(1) + "], [" - + srcTable.getColumnName(2) + "],[" + srcTable.getColumnName(3) + "];"); - DBResultSet dstResultSet = con.createStatement().executeQuery( - "SELECT * FROM " + destTable.getEscapedTableName() + " ORDER BY [" + destTable.getColumnName(1) + "], [" - + destTable.getColumnName(2) + "],[" + destTable.getColumnName(3) + "];"); - - while (srcResultSet.next() && dstResultSet.next()) { - for (int i = 0; i < destTable.getColumns().size(); i++) { - SQLServerResultSetMetaData srcMeta = (SQLServerResultSetMetaData) ((ResultSet) srcResultSet.product()) - .getMetaData(); - SQLServerResultSetMetaData destMeta = (SQLServerResultSetMetaData) ((ResultSet) dstResultSet.product()) - .getMetaData(); - - int srcJDBCTypeInt = srcMeta.getColumnType(i + 1); - int destJDBCTypeInt = destMeta.getColumnType(i + 1); - - // verify column types - if (srcJDBCTypeInt != destJDBCTypeInt) { - fail("Souce table and Destination table have different number of columns."); + try (DBResultSet srcResultSet = stmt.executeQuery( + "SELECT * FROM " + srcTable.getEscapedTableName() + " ORDER BY [" + srcTable.getColumnName(1) + + "], [" + srcTable.getColumnName(2) + "],[" + srcTable.getColumnName(3) + "];"); + DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destTable.getEscapedTableName() + + " ORDER BY [" + destTable.getColumnName(1) + "], [" + destTable.getColumnName(2) + "],[" + + destTable.getColumnName(3) + "];")) { + + while (srcResultSet.next() && dstResultSet.next()) { + for (int i = 0; i < destTable.getColumns().size(); i++) { + SQLServerResultSetMetaData srcMeta = (SQLServerResultSetMetaData) ((ResultSet) srcResultSet + .product()).getMetaData(); + SQLServerResultSetMetaData destMeta = (SQLServerResultSetMetaData) ((ResultSet) dstResultSet + .product()).getMetaData(); + + int srcJDBCTypeInt = srcMeta.getColumnType(i + 1); + int destJDBCTypeInt = destMeta.getColumnType(i + 1); + + // verify column types + if (srcJDBCTypeInt != destJDBCTypeInt) { + fail("Souce table and Destination table have different number of columns."); + } + + Object expectedValue = srcResultSet.getObject(i + 1); + Object actualValue = dstResultSet.getObject(i + 1); + + compareExpectedAndActual(destJDBCTypeInt, expectedValue, actualValue); + } } - - Object expectedValue = srcResultSet.getObject(i + 1); - Object actualValue = dstResultSet.getObject(i + 1); - - compareExpectedAndActual(destJDBCTypeInt, expectedValue, actualValue); } } } 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 ea9e2d8f7..a18625365 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java @@ -51,9 +51,8 @@ private void testBulkCopyResultSet(boolean setSelectMethod, Integer resultSetTyp 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()); + .createStatement(resultSetType, resultSetConcurrency) : connnection.createStatement(); + ResultSet rs = statement.executeQuery("select * from " + tableSrc.getEscapedTableName())) { SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); bcOperation.setDestinationTableName(tableDest.getEscapedTableName()); @@ -62,9 +61,9 @@ private void testBulkCopyResultSet(boolean setSelectMethod, Integer resultSetTyp ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, tableDest); + } finally { + terminateVariation(); } - - terminateVariation(); } private void setupVariation() throws SQLException { 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 34b1bee80..377601093 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java @@ -92,7 +92,6 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, bo fail(ex.getMessage()); } finally { stmt.dropTable(destinationTable); - con.close(); } } catch (SQLException ex) { fail(ex.getMessage()); @@ -190,7 +189,6 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, DB } } finally { stmt.dropTable(destinationTable); - con.close(); } } catch (SQLException e) { if (!fail) { @@ -251,7 +249,6 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, DB if (dropDest) { stmt.dropTable(destinationTable); } - con.close(); } } catch (SQLException ex) { if (!fail) { 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 a8b220568..d34a566fd 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java @@ -55,7 +55,6 @@ public void testConnectionIsClosed() throws SQLException { assertTrue(!conn.isClosed(), TestResource.getResource("R_connShouldNotBeClosed")); conn.close(); assertTrue(conn.isClosed(), TestResource.getResource("R_connShouldNotBeOpen")); - } } 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 a3345a7ff..856e2b905 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -130,28 +130,30 @@ public void getSetNullWithTypeVarchar() 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", "world"); - cs1.setString("p1", "hello"); - rs = cs1.executeQuery(); - rs.next(); - assertEquals("helloworld", rs.getString(1)); - + try (CallableStatement cs = connection.prepareCall(call)) { + cs.setString("p2", "world"); + cs.setString("p1", "hello"); + try (ResultSet rs = cs.executeQuery()) { + rs.next(); + assertEquals("helloworld", 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)); + try (CallableStatement cs = connection.prepareCall(call)) { + cs.setString("@p2", "world!"); + cs.setString("@p1", "Hello "); + try (ResultSet rs = cs.executeQuery()) { + rs.next(); + assertEquals("Hello world!", rs.getString(1)); + } + } // sanity check: unrecognized parameter name - CallableStatement cs3 = connection.prepareCall(call); - try { - cs3.setString("@whatever", "test"); + try (CallableStatement cs = connection.prepareCall(call)) { + cs.setString("@whatever", "test"); fail(TestResource.getResource("R_shouldThrowException")); } catch (SQLException sse) { @@ -162,7 +164,6 @@ public void inputParamsTest() throws SQLException { fail(TestResource.getResource("R_unexpectedExceptionContent")); } } - } /** 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 91d6d3652..9881ab9c3 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -208,18 +208,19 @@ public void testConnectionPoolGetTwice() throws SQLException { 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); - // 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, TestResource.getResource("R_errorCalled")); - // check to make sure that connection is not closed. - assertTrue(!con.isClosed(), TestResource.getResource("R_connectionIsClosed")); - stmt.close(); - con.close(); - // check to make sure that connection is closed. - assertTrue(con.isClosed(), TestResource.getResource("R_connectionIsNotClosed")); + try (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, TestResource.getResource("R_errorCalled")); + // check to make sure that connection is not closed. + assertTrue(!con.isClosed(), TestResource.getResource("R_connectionIsClosed")); + stmt.close(); + con.close(); + // check to make sure that connection is closed. + assertTrue(con.isClosed(), TestResource.getResource("R_connectionIsNotClosed")); + } } @Test @@ -229,8 +230,8 @@ public void testConnectionClosed() throws SQLException { SQLServerDataSource mds = new SQLServerDataSource(); mds.setURL(connectionString); - Connection con = mds.getConnection(); - try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + try (Connection con = mds.getConnection(); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { boolean exceptionThrown = false; try { stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); @@ -238,12 +239,12 @@ public void testConnectionClosed() throws SQLException { exceptionThrown = true; } assertTrue(exceptionThrown, TestResource.getResource("R_expectedExceptionNotThrown")); + + // check to make sure that connection is closed. + assertTrue(con.isClosed(), TestResource.getResource("R_connectionIsNotClosed")); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } - - // check to make sure that connection is closed. - assertTrue(con.isClosed(), TestResource.getResource("R_connectionIsNotClosed")); } @Test @@ -340,23 +341,22 @@ public void testDeadConnection() throws SQLException { @Test public void testClientConnectionId() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - assertTrue(conn.getClientConnectionId() != null, TestResource.getResource("R_clientConnectionIdNull")); - conn.close(); - try { - // Call getClientConnectionId on a closed connection, should raise exception - conn.getClientConnectionId(); - throw new Exception(TestResource.getResource("R_noExceptionClosedConnection")); - } catch (SQLException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_connectionIsClosed"), - TestResource.getResource("R_wrongExceptionMessage")); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + assertTrue(conn.getClientConnectionId() != null, TestResource.getResource("R_clientConnectionIdNull")); + conn.close(); + try { + // Call getClientConnectionId on a closed connection, should raise exception + conn.getClientConnectionId(); + throw new Exception(TestResource.getResource("R_noExceptionClosedConnection")); + } catch (SQLException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_connectionIsClosed"), + TestResource.getResource("R_wrongExceptionMessage")); + } } - conn = null; - try { - // Wrong database, ClientConnectionId should be available in error message - conn = (SQLServerConnection) DriverManager.getConnection( - connectionString + ";databaseName=" + RandomUtil.getIdentifierForDB("DataBase") + ";"); + // Wrong database, ClientConnectionId should be available in error message + try (SQLServerConnection conn = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";databaseName=" + RandomUtil.getIdentifierForDB("DataBase") + ";")) { conn.close(); } catch (SQLException e) { @@ -364,10 +364,9 @@ public void testClientConnectionId() throws Exception { TestResource.getResource("R_unexpectedWrongDB")); } - try { - // Nonexist host, ClientConnectionId should not be available in error message - conn = (SQLServerConnection) DriverManager.getConnection( - connectionString + ";instanceName=" + RandomUtil.getIdentifier("Instance") + ";logintimeout=5;"); + // Nonexist host, ClientConnectionId should not be available in error message + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection( + connectionString + ";instanceName=" + RandomUtil.getIdentifier("Instance") + ";logintimeout=5;")) { conn.close(); } catch (SQLException e) { @@ -380,7 +379,6 @@ public void testClientConnectionId() throws Exception { public void testIncorrectDatabase() throws SQLException { long timerStart = 0; long timerEnd = 0; - Connection con = null; final long milsecs = threshHoldForNoRetryInMilliseconds; try { SQLServerDataSource ds = new SQLServerDataSource(); @@ -388,25 +386,25 @@ public void testIncorrectDatabase() throws SQLException { ds.setLoginTimeout(loginTimeOutInSeconds); ds.setDatabaseName(RandomUtil.getIdentifier("DataBase")); timerStart = System.currentTimeMillis(); - con = ds.getConnection(); + try (Connection con = ds.getConnection()) { + + long timeDiff = timerEnd - timerStart; + assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); + + MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); + Object[] msgArgs = {milsecs / 1000}; + assertTrue(timeDiff <= milsecs, form.format(msgArgs)); + } } catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_cannotOpenDatabase"))); timerEnd = System.currentTimeMillis(); } - - long timeDiff = timerEnd - timerStart; - assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); - - MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); - Object[] msgArgs = {milsecs / 1000}; - assertTrue(timeDiff <= milsecs, form.format(msgArgs)); } @Test public void testIncorrectUserName() throws SQLException { long timerStart = 0; long timerEnd = 0; - Connection con = null; final long milsecs = threshHoldForNoRetryInMilliseconds; try { SQLServerDataSource ds = new SQLServerDataSource(); @@ -414,24 +412,23 @@ public void testIncorrectUserName() throws SQLException { ds.setLoginTimeout(loginTimeOutInSeconds); ds.setUser(RandomUtil.getIdentifier("User")); timerStart = System.currentTimeMillis(); - con = ds.getConnection(); + try (Connection con = ds.getConnection()) { + long timeDiff = timerEnd - timerStart; + assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); + MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); + Object[] msgArgs = {milsecs / 1000}; + assertTrue(timeDiff <= milsecs, form.format(msgArgs)); + } } catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_loginFailed"))); timerEnd = System.currentTimeMillis(); } - - long timeDiff = timerEnd - timerStart; - assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); - MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); - Object[] msgArgs = {milsecs / 1000}; - assertTrue(timeDiff <= milsecs, form.format(msgArgs)); } @Test public void testIncorrectPassword() throws SQLException { long timerStart = 0; long timerEnd = 0; - Connection con = null; final long milsecs = threshHoldForNoRetryInMilliseconds; try { SQLServerDataSource ds = new SQLServerDataSource(); @@ -439,24 +436,23 @@ public void testIncorrectPassword() throws SQLException { ds.setLoginTimeout(loginTimeOutInSeconds); ds.setPassword(RandomUtil.getIdentifier("Password")); timerStart = System.currentTimeMillis(); - con = ds.getConnection(); + try (Connection con = ds.getConnection()) { + long timeDiff = timerEnd - timerStart; + assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); + MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); + Object[] msgArgs = {milsecs / 1000}; + assertTrue(timeDiff <= milsecs, form.format(msgArgs)); + } } catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_loginFailed"))); timerEnd = System.currentTimeMillis(); } - - long timeDiff = timerEnd - timerStart; - assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); - MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); - Object[] msgArgs = {milsecs / 1000}; - assertTrue(timeDiff <= milsecs, form.format(msgArgs)); } @Test public void testInvalidCombination() throws SQLException { long timerStart = 0; long timerEnd = 0; - Connection con = null; final long milsecs = threshHoldForNoRetryInMilliseconds; try { SQLServerDataSource ds = new SQLServerDataSource(); @@ -465,17 +461,18 @@ public void testInvalidCombination() throws SQLException { ds.setMultiSubnetFailover(true); ds.setFailoverPartner(RandomUtil.getIdentifier("FailoverPartner")); timerStart = System.currentTimeMillis(); - con = ds.getConnection(); + try (Connection con = ds.getConnection()) { + + long timeDiff = timerEnd - timerStart; + assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); + MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); + Object[] msgArgs = {milsecs / 1000}; + assertTrue(timeDiff <= milsecs, form.format(msgArgs)); + } } catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_connectMirrored"))); timerEnd = System.currentTimeMillis(); } - - long timeDiff = timerEnd - timerStart; - assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); - MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedMoreSeconds")); - Object[] msgArgs = {milsecs / 1000}; - assertTrue(timeDiff <= milsecs, form.format(msgArgs)); } @Test @@ -483,7 +480,6 @@ public void testInvalidCombination() throws SQLException { public void testIncorrectDatabaseWithFailoverPartner() throws SQLException { long timerStart = 0; long timerEnd = 0; - Connection con = null; try { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); @@ -491,45 +487,50 @@ public void testIncorrectDatabaseWithFailoverPartner() throws SQLException { ds.setDatabaseName(RandomUtil.getIdentifierForDB("DB")); ds.setFailoverPartner(RandomUtil.getIdentifier("FailoverPartner")); timerStart = System.currentTimeMillis(); - con = ds.getConnection(); + try (Connection con = ds.getConnection()) { + + long timeDiff = timerEnd - timerStart; + assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); + MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedLessSeconds")); + Object[] msgArgs = {loginTimeOutInSeconds - 1}; + assertTrue(timeDiff >= ((loginTimeOutInSeconds - 1) * 1000), form.format(msgArgs)); + } } catch (Exception e) { timerEnd = System.currentTimeMillis(); } - - long timeDiff = timerEnd - timerStart; - assertTrue(con == null, TestResource.getResource("R_shouldNotConnect")); - MessageFormat form = new MessageFormat(TestResource.getResource("R_exitedLessSeconds")); - Object[] msgArgs = {loginTimeOutInSeconds - 1}; - assertTrue(timeDiff >= ((loginTimeOutInSeconds - 1) * 1000), form.format(msgArgs)); } @Test public void testAbortBadParam() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - try { - conn.abort(null); - } catch (SQLException e) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_invalidArgumentExecutor"))); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try { + conn.abort(null); + } catch (SQLException e) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_invalidArgumentExecutor"))); + } } } @Test public void testAbort() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - Executor executor = Executors.newFixedThreadPool(2); - conn.abort(executor); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + Executor executor = Executors.newFixedThreadPool(2); + conn.abort(executor); + } } @Test public void testSetSchema() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - conn.setSchema(RandomUtil.getIdentifier("schema")); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + conn.setSchema(RandomUtil.getIdentifier("schema")); + } } @Test public void testGetSchema() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - conn.getSchema(); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + conn.getSchema(); + } } static Boolean isInterrupted = false; @@ -550,9 +551,7 @@ public void run() { ds.setServerName("invalidServerName" + UUID.randomUUID()); ds.setLoginTimeout(5); - try { - ds.getConnection(); - } catch (SQLException e) { + try (Connection con = ds.getConnection()) {} catch (SQLException e) { isInterrupted = Thread.currentThread().isInterrupted(); } } 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 b7b098a1b..ea17b9408 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -153,17 +153,20 @@ public void testConnectionPoolClientConnectionId() throws SQLException { PooledConnection pc = null; try { pc = ds.getPooledConnection(); - ISQLServerConnection con = (ISQLServerConnection) pc.getConnection(); + UUID Id1 = null; + UUID Id2 = null; - UUID Id1 = con.getClientConnectionId(); - assertTrue(Id1 != null, TestResource.getResource("R_connectionNotClosedWithPoolClose")); - con.close(); + try (ISQLServerConnection con = (ISQLServerConnection) pc.getConnection()) { - // now reget the connection - ISQLServerConnection con2 = (ISQLServerConnection) pc.getConnection(); + Id1 = con.getClientConnectionId(); + assertTrue(Id1 != null, TestResource.getResource("R_connectionNotClosedWithPoolClose")); + } + + // now re-get the connection + try (ISQLServerConnection con = (ISQLServerConnection) pc.getConnection()) { - UUID Id2 = con2.getClientConnectionId(); - con2.close(); + Id2 = con.getClientConnectionId(); + } assertEquals(Id1, Id2, TestResource.getResource("R_idFromPoolNotSame")); } finally { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java index 8f9c76442..ccaa764d4 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -192,16 +192,14 @@ public void testOpenTransactions() throws SQLException { try (ResultSet rs = con.createStatement().executeQuery("SELECT * from " + tableName)) { assertTrue(!rs.isBeforeFirst(), "Should not have returned a result set."); + } finally { + if (null != tableName) { + TestUtils.dropTableIfExists(tableName, stmt); + } } } } catch (Exception e) { e.printStackTrace(); - } finally { - if (null != tableName) { - try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); - } - } } } @@ -213,73 +211,63 @@ public void testOpenTransactions() throws SQLException { @SuppressWarnings("resource") @Test public void testStatements() throws SQLException { - Statement stmt = null; - ResultSet rs = null; - Statement stmt1 = null; - PreparedStatement ps = null; - CallableStatement cs = null; - ResultSet rs1 = null; String tableName = null; try (SQLServerConnection con = connect();) { if (TestUtils.isJDBC43OrGreater(con)) { - stmt1 = con.createStatement(); - con.beginRequest(); - stmt = con.createStatement(); - rs = stmt.executeQuery("SELECT 1"); - rs.next(); - assertEquals(1, rs.getInt(1)); - con.endRequest(); - - assertTrue(!stmt1.isClosed(), - "Statement created outside of beginRequest()/endRequest() block should not be closed."); - assertTrue(stmt.isClosed(), - "Statment created inside beginRequest()/endRequest() block should be closed after endRequest()."); - assertTrue(rs.isClosed(), "ResultSet should be closed after endRequest()."); - stmt1.close(); + try (Statement stmt1 = con.createStatement()) { + con.beginRequest(); + try (Statement stmt = con.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT 1")) { + rs.next(); + assertEquals(1, rs.getInt(1)); + con.endRequest(); + + assertTrue(!stmt1.isClosed(), + "Statement created outside of beginRequest()/endRequest() block should not be closed."); + assertTrue(stmt.isClosed(), + "Statment created inside beginRequest()/endRequest() block should be closed after endRequest()."); + assertTrue(rs.isClosed(), "ResultSet should be closed after endRequest()."); + } + } + } // Multiple statements inside beginRequest()/endRequest() block con.beginRequest(); - stmt = con.createStatement(); - tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundary")); - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col int)"); - ps = con.prepareStatement("INSERT INTO " + tableName + " values (?)"); - ps.setInt(1, 2); - ps.executeUpdate(); - - stmt1 = con.createStatement(); - rs1 = stmt1.executeQuery("SELECT * FROM " + tableName); - rs1.next(); - assertEquals(2, rs1.getInt(1)); - - cs = con.prepareCall("{call sp_server_info}"); - cs.execute(); - con.endRequest(); - - assertTrue(stmt.isClosed()); - assertTrue(ps.isClosed()); - assertTrue(stmt1.isClosed()); - assertTrue(cs.isClosed()); - assertTrue(rs1.isClosed()); - } - } finally { - if (null != stmt) { - stmt.close(); - } - if (null != stmt1) { - stmt1.close(); - } - if (null != ps) { - ps.close(); - } - if (null != cs) { - cs.close(); - } - if (null != tableName) { - try (Connection con = DriverManager.getConnection(connectionString); Statement statement = con.createStatement()) { - TestUtils.dropTableIfExists(tableName, statement); + try (Statement stmt = con.createStatement()) { + tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundary")); + TestUtils.dropTableIfExists(tableName, stmt); + stmt.executeUpdate("CREATE TABLE " + tableName + " (col int)"); + try (PreparedStatement ps = con.prepareStatement("INSERT INTO " + tableName + " values (?)")) { + ps.setInt(1, 2); + ps.executeUpdate(); + + try (Statement stmt1 = con.createStatement(); + ResultSet rs = stmt1.executeQuery("SELECT * FROM " + tableName)) { + rs.next(); + assertEquals(2, rs.getInt(1)); + TestUtils.dropTableIfExists(tableName, stmt); + + try (CallableStatement cs = con.prepareCall("{call sp_server_info}")) { + cs.execute(); + con.endRequest(); + + assertTrue(stmt.isClosed()); + assertTrue(ps.isClosed()); + assertTrue(stmt1.isClosed()); + assertTrue(cs.isClosed()); + assertTrue(rs.isClosed()); + } + } + } + } finally { + if (null != tableName) { + try (Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(tableName, stmt); + } + } } + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java index a7f19a6d7..6ec0eb567 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java @@ -97,15 +97,14 @@ public void testFOInstanceResolution2() throws SQLException { */ @Test public void testQueryTimeout() throws Exception { - SQLServerConnection conn = null; - try { - conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); - - conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";"); + } + + try (SQLServerConnection conn = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";")) { try (Statement stmt = conn.createStatement()) { stmt.execute("exec " + waitForDelaySPName); @@ -125,12 +124,8 @@ public void testQueryTimeout() throws Exception { } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != conn) { - conn.close(); - } } - } + } /** * Tests sanity of connection property. @@ -139,16 +134,15 @@ public void testQueryTimeout() throws Exception { */ @Test public void testCancelQueryTimeout() throws Exception { - SQLServerConnection conn = null; - try { - conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); + } - conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";queryTimeout=" - + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + ";"); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + ";")) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.execute("exec " + waitForDelaySPName); @@ -160,6 +154,7 @@ public void testCancelQueryTimeout() throws Exception { assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), TestResource.getResource("R_invalidExceptionMessage")); } + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.execute("SELECT @@version"); } catch (Exception e) { @@ -167,10 +162,6 @@ public void testCancelQueryTimeout() throws Exception { } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != conn) { - conn.close(); - } } } @@ -181,15 +172,13 @@ public void testCancelQueryTimeout() throws Exception { */ @Test public void testCancelQueryTimeoutOnStatement() throws Exception { - SQLServerConnection conn = null; - - try { - conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); + } - conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";"); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";")) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.setQueryTimeout(waitForDelaySeconds / 2); @@ -203,6 +192,7 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), TestResource.getResource("R_invalidExceptionMessage")); } + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.execute("SELECT @@version"); } catch (Exception e) { @@ -210,10 +200,6 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != conn) { - conn.close(); - } } } @@ -224,17 +210,14 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { */ @Test public void testSocketTimeout() throws Exception { - SQLServerConnection conn = null; - - try { - - conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); + } - conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";")) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.execute("exec " + waitForDelaySPName); @@ -246,6 +229,7 @@ public void testSocketTimeout() throws Exception { assertEquals(e.getMessage(), TestResource.getResource("R_readTimedOut"), TestResource.getResource("R_invalidExceptionMessage")); } + try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.execute("SELECT @@version"); } catch (SQLException e) { @@ -254,10 +238,6 @@ public void testSocketTimeout() throws Exception { } } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); - } finally { - if (null != conn) { - conn.close(); - } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java index af5a227eb..1be8e5c34 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java @@ -12,6 +12,8 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; +import java.sql.Connection; +import java.sql.ResultSet; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -20,7 +22,6 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; -import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -33,11 +34,8 @@ @RunWith(JUnitPlatform.class) public class BulkCopyWithSqlVariantTest extends AbstractTest { - static SQLServerConnection con = null; - static Statement stmt = null; static String tableName = "sqlVariantTestSrcTable"; static String destTableName = "sqlVariantDestTable"; - static SQLServerResultSet rs = null; /** * Test integer value @@ -46,18 +44,24 @@ public class BulkCopyWithSqlVariantTest extends AbstractTest { */ @Test public void bulkCopyTestInt() throws SQLException { - int col1Value = 5; - beforeEachSetup("int", col1Value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getInt(1), 5); + try (Connection con = DriverManager.getConnection(connectionString)) { + + int col1Value = 5; + beforeEachSetup("int", col1Value); + try (Statement stmt = con.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getInt(1), 5); + } + } + } } } @@ -68,21 +72,28 @@ public void bulkCopyTestInt() throws SQLException { */ @Test public void bulkCopyTestSmallInt() throws SQLException { - int col1Value = 5; - beforeEachSetup("smallint", col1Value); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getShort(1), 5); + try (Connection con = DriverManager.getConnection(connectionString)) { + + int col1Value = 5; + beforeEachSetup("smallint", col1Value); + + try (Statement stmt = con.createStatement()) { + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getShort(1), 5); + } + bulkCopy.close(); + } + } } - bulkCopy.close(); } /** @@ -92,20 +103,28 @@ public void bulkCopyTestSmallInt() throws SQLException { */ @Test public void bulkCopyTestTinyint() throws SQLException { - int col1Value = 5; - beforeEachSetup("tinyint", col1Value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getByte(1), 5); + try (Connection con = DriverManager.getConnection(connectionString)) { + + int col1Value = 5; + beforeEachSetup("tinyint", col1Value); + + try (Statement stmt = con.createStatement()) { + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getByte(1), 5); + } + bulkCopy.close(); + } + } } - bulkCopy.close(); } /** @@ -115,21 +134,27 @@ public void bulkCopyTestTinyint() throws SQLException { */ @Test public void bulkCopyTestBigint() throws SQLException { - int col1Value = 5; - beforeEachSetup("bigint", col1Value); + try (Connection con = DriverManager.getConnection(connectionString)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + int col1Value = 5; + beforeEachSetup("bigint", col1Value); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + try (Statement stmt = con.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getLong(1), col1Value); - } - } + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getLong(1), col1Value); + } + } + } + + }} /** * test float value @@ -138,19 +163,27 @@ public void bulkCopyTestBigint() throws SQLException { */ @Test public void bulkCopyTestFloat() throws SQLException { - int col1Value = 5; - beforeEachSetup("float", col1Value); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getDouble(1), col1Value); + try (Connection con = DriverManager.getConnection(connectionString)) { + + int col1Value = 5; + beforeEachSetup("float", col1Value); + + try (Statement stmt = con.createStatement()) { + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getDouble(1), col1Value); + } + } + } } } @@ -161,20 +194,28 @@ public void bulkCopyTestFloat() throws SQLException { */ @Test public void bulkCopyTestReal() throws SQLException { - int col1Value = 5; - beforeEachSetup("real", col1Value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getFloat(1), col1Value); + try (Connection con = DriverManager.getConnection(connectionString)) { + + int col1Value = 5; + beforeEachSetup("real", col1Value); + + try (Statement stmt = con.createStatement()) { + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getFloat(1), col1Value); + } + } + } } - } /** @@ -184,21 +225,27 @@ public void bulkCopyTestReal() throws SQLException { */ @Test public void bulkCopyTestMoney() throws SQLException { - String col1Value = "126.1230"; - beforeEachSetup("money", col1Value); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getMoney(1), new BigDecimal(col1Value)); + try (Connection con = DriverManager.getConnection(connectionString)) { + + String col1Value = "126.1230"; + beforeEachSetup("money", col1Value); + + try (Statement stmt = con.createStatement()) { + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getMoney(1), new BigDecimal(col1Value)); + } + } + } } - } /** @@ -208,27 +255,31 @@ public void bulkCopyTestMoney() throws SQLException { */ @Test public void bulkCopyTestSmallmoney() throws SQLException { - String col1Value = "126.1230"; - String destTableName = "dest_sqlVariant"; - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "smallmoney" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getSmallMoney(1), new BigDecimal(col1Value)); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "126.1230"; + String destTableName = "dest_sqlVariant"; + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); + stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); + stmt.executeUpdate( + "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "smallmoney" + ") )"); + stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getSmallMoney(1), new BigDecimal(col1Value)); + } + } } - } /** @@ -238,53 +289,61 @@ public void bulkCopyTestSmallmoney() throws SQLException { */ @Test public void bulkCopyTestDate() throws SQLException { - String col1Value = "2015-05-05"; - beforeEachSetup("date", "'" + col1Value + "'"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("" + rs.getDate(1), col1Value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "2015-05-05"; + beforeEachSetup("date", "'" + col1Value + "'"); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("" + rs.getDate(1), col1Value); + } + } } - } /** - * Test bulkcoping two column with sql_variant datatype + * Test bulkcopying two column with sql_variant datatype * * @throws SQLException */ @Test public void bulkCopyTestTwoCols() throws SQLException { - String col1Value = "2015-05-05"; - String col2Value = "126.1230"; - String destTableName = "dest_sqlVariant"; - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST ('" + col1Value + "' AS " + "date" - + ")" + ",CAST (" + col2Value + " AS " + "smallmoney" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant, col2 sql_variant)"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("" + rs.getDate(1), col1Value); - assertEquals(rs.getSmallMoney(2), new BigDecimal(col2Value)); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "2015-05-05"; + String col2Value = "126.1230"; + String destTableName = "dest_sqlVariant"; + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); + stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); + stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST ('" + col1Value + "' AS " + + "date" + ")" + ",CAST (" + col2Value + " AS " + "smallmoney" + ") )"); + stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant, col2 sql_variant)"); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("" + rs.getDate(1), col1Value); + assertEquals(rs.getSmallMoney(2), new BigDecimal(col2Value)); + } + } } - } /** @@ -294,20 +353,23 @@ public void bulkCopyTestTwoCols() throws SQLException { */ @Test public void bulkCopyTestTimeWithScale() throws SQLException { - String col1Value = "'12:26:27.1452367'"; - beforeEachSetup("time(2)", col1Value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("" + rs.getString(1), "12:26:27.15"); // getTime does not work + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "'12:26:27.1452367'"; + beforeEachSetup("time(2)", col1Value); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("" + rs.getString(1), "12:26:27.15"); // getTime does not work + } + } } - } /** @@ -317,22 +379,25 @@ public void bulkCopyTestTimeWithScale() throws SQLException { */ @Test public void bulkCopyTestChar() throws SQLException { - String col1Value = "'sample'"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - beforeEachSetup("char", col1Value); + String col1Value = "'sample'"; - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + beforeEachSetup("char", col1Value); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("'" + rs.getString(1).trim() + "'", col1Value); // adds space between + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("'" + rs.getString(1).trim() + "'", col1Value); // adds space between + } + } } - } /** @@ -342,21 +407,24 @@ public void bulkCopyTestChar() throws SQLException { */ @Test public void bulkCopyTestNchar() throws SQLException { - String col1Value = "'a'"; - - beforeEachSetup("nchar", col1Value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("'" + rs.getNString(1).trim() + "'", col1Value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "'a'"; + + beforeEachSetup("nchar", col1Value); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("'" + rs.getNString(1).trim() + "'", col1Value); + } + } } - } /** @@ -366,22 +434,25 @@ public void bulkCopyTestNchar() throws SQLException { */ @Test public void bulkCopyTestVarchar() throws SQLException { - String col1Value = "'hello'"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - beforeEachSetup("varchar", col1Value); + String col1Value = "'hello'"; - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + beforeEachSetup("varchar", col1Value); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("'" + rs.getString(1).trim() + "'", col1Value); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("'" + rs.getString(1).trim() + "'", col1Value); + } + } } - } /** @@ -391,21 +462,24 @@ public void bulkCopyTestVarchar() throws SQLException { */ @Test public void bulkCopyTestNvarchar() throws SQLException { - String col1Value = "'hello'"; - beforeEachSetup("nvarchar", col1Value); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("'" + rs.getString(1).trim() + "'", col1Value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "'hello'"; + beforeEachSetup("nvarchar", col1Value); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("'" + rs.getString(1).trim() + "'", col1Value); + } + } } - } /** @@ -415,19 +489,24 @@ public void bulkCopyTestNvarchar() throws SQLException { */ @Test public void bulkCopyTestBinary20() throws SQLException { - String col1Value = "hello"; - beforeEachSetup("binary(20)", "'" + col1Value + "'"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "hello"; + beforeEachSetup("binary(20)", "'" + col1Value + "'"); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); + } + } } } @@ -438,19 +517,24 @@ public void bulkCopyTestBinary20() throws SQLException { */ @Test public void bulkCopyTestVarbinary20() throws SQLException { - String col1Value = "hello"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "hello"; - beforeEachSetup("varbinary(20)", "'" + col1Value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + beforeEachSetup("varbinary(20)", "'" + col1Value + "'"); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); + } + } } } @@ -461,18 +545,22 @@ public void bulkCopyTestVarbinary20() throws SQLException { */ @Test public void bulkCopyTestVarbinary8000() throws SQLException { - String col1Value = "hello"; - beforeEachSetup("binary(8000)", "'" + col1Value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "hello"; + beforeEachSetup("binary(8000)", "'" + col1Value + "'"); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); + } + } } } @@ -483,18 +571,23 @@ public void bulkCopyTestVarbinary8000() throws SQLException { */ @Test // TODO: check bitnull public void bulkCopyTestBitNull() throws SQLException { - beforeEachSetup("bit", null); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getBoolean(1), false); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + beforeEachSetup("bit", null); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getBoolean(1), false); + } + } } } @@ -505,18 +598,23 @@ public void bulkCopyTestBitNull() throws SQLException { */ @Test public void bulkCopyTestBit() throws SQLException { - int col1Value = 5000; - beforeEachSetup("bit", col1Value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getBoolean(1), true); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + int col1Value = 5000; + beforeEachSetup("bit", col1Value); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getBoolean(1), true); + } + } } } @@ -527,22 +625,26 @@ public void bulkCopyTestBit() throws SQLException { */ @Test public void bulkCopyTestDatetime() throws SQLException { - String col1Value = "2015-05-08 12:26:24.0"; - beforeEachSetup("datetime", "'" + col1Value + "'"); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + String col1Value = "2015-05-08 12:26:24.0"; + beforeEachSetup("datetime", "'" + col1Value + "'"); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("" + rs.getDateTime(1), col1Value); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } - } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("" + rs.getDateTime(1), col1Value); + } + } + } } /** @@ -552,21 +654,25 @@ public void bulkCopyTestDatetime() throws SQLException { */ @Test public void bulkCopyTestSmalldatetime() throws SQLException { - String col1Value = "2015-05-08 12:26:24"; - beforeEachSetup("smalldatetime", "'" + col1Value + "'"); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + String col1Value = "2015-05-08 12:26:24"; + beforeEachSetup("smalldatetime", "'" + col1Value + "'"); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("" + rs.getSmallDateTime(1), "2015-05-08 12:26:00.0"); - } + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("" + rs.getSmallDateTime(1), "2015-05-08 12:26:00.0"); + } + } + } } /** @@ -576,21 +682,25 @@ public void bulkCopyTestSmalldatetime() throws SQLException { */ @Test public void bulkCopyTestDatetime2() throws SQLException { - String col1Value = "2015-05-08 12:26:24.12645"; - beforeEachSetup("datetime2(2)", "'" + col1Value + "'"); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + String col1Value = "2015-05-08 12:26:24.12645"; + beforeEachSetup("datetime2(2)", "'" + col1Value + "'"); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("" + rs.getTimestamp(1), "2015-05-08 12:26:24.13"); - } + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("" + rs.getTimestamp(1), "2015-05-08 12:26:24.13"); + } + } + } } /** @@ -600,24 +710,29 @@ public void bulkCopyTestDatetime2() throws SQLException { */ @Test public void bulkCopyTestTime() throws SQLException { - String col1Value = "'12:26:27.1452367'"; - String destTableName = "dest_sqlVariant"; - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "time(2)" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - rs.next(); - assertEquals("" + rs.getObject(1).toString(), "12:26:27"); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + String col1Value = "'12:26:27.1452367'"; + String destTableName = "dest_sqlVariant"; + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); + stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); + stmt.executeUpdate( + "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "time(2)" + ") )"); + stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + rs.next(); + assertEquals("" + rs.getObject(1).toString(), "12:26:27"); + } + } } /** @@ -627,19 +742,24 @@ public void bulkCopyTestTime() throws SQLException { */ @Test public void bulkCopyTestReadGUID() throws SQLException { - String col1Value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; - beforeEachSetup("uniqueidentifier", "'" + col1Value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); + String col1Value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; + beforeEachSetup("uniqueidentifier", "'" + col1Value + "'"); + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals("" + rs.getUniqueIdentifier(1), col1Value); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals("" + rs.getUniqueIdentifier(1), col1Value); + + } + } } } @@ -650,45 +770,41 @@ public void bulkCopyTestReadGUID() throws SQLException { */ @Test public void bulkCopyTestVarChar8000() throws SQLException { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < 8000; i++) { - buffer.append("a"); - } - String col1Value = buffer.toString(); - beforeEachSetup("varchar(8000)", "'" + col1Value + "'"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); - bulkCopy.writeToServer(rs); - bulkCopy.close(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName); - while (rs.next()) { - assertEquals(rs.getString(1), col1Value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < 8000; i++) { + buffer.append("a"); + } + String col1Value = buffer.toString(); + beforeEachSetup("varchar(8000)", "'" + col1Value + "'"); + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + bulkCopy.setDestinationTableName(destTableName); + bulkCopy.writeToServer(rs); + bulkCopy.close(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + while (rs.next()) { + assertEquals(rs.getString(1), col1Value); + } + } } } private void beforeEachSetup(String colType, Object colValue) throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + "(col1) values (CAST (" + colValue + " AS " + colType + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); - } - - /** - * Prepare test - * - * @throws SQLException - * @throws SecurityException - * @throws IOException - */ - @BeforeAll - public static void setupHere() throws SQLException, SecurityException, IOException { - con = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = con.createStatement(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); + stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); + stmt.executeUpdate( + "INSERT into " + tableName + "(col1) values (CAST (" + colValue + " AS " + colType + ") )"); + stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + } } /** @@ -698,19 +814,9 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != rs) { - rs.close(); - } - - if (null != con) { - con.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(destTableName, stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java index b06a1ed86..92b22d357 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java @@ -39,26 +39,23 @@ public class DateAndTimeTypeTest extends AbstractTest { private static final Time TIME_TO_TEST = new java.sql.Time(74096000L); private static final Timestamp TIMESTAMP_TO_TEST = new java.sql.Timestamp(61494838496000L); - static Statement stmt = null; - static Connection connection = null; - static PreparedStatement pstmt = null; - static ResultSet rs = null; - /** * Test query with date */ @Test public void testQueryDate() throws SQLException { - String sPrepStmt = "select * from dateandtime where my_date = ?"; - pstmt = connection.prepareStatement(sPrepStmt); - pstmt.setDate(1, DATE_TO_TEST); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { - rs = pstmt.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); - rs.close(); - pstmt.close(); + String sPrepStmt = "select * from dateandtime where my_date = ?"; + try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { + pstmt.setDate(1, DATE_TO_TEST); + try (ResultSet rs = pstmt.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); + } + } + } } /** @@ -66,15 +63,18 @@ public void testQueryDate() throws SQLException { */ @Test public void testQueryTimestamp() throws SQLException { - String sPrepStmt = "select * from dateandtime where my_timestamp = ?"; - pstmt = connection.prepareStatement(sPrepStmt); - pstmt.setTimestamp(1, TIMESTAMP_TO_TEST); - - rs = pstmt.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); - rs.close(); - pstmt.close(); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + + String sPrepStmt = "select * from dateandtime where my_timestamp = ?"; + try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { + pstmt.setTimestamp(1, TIMESTAMP_TO_TEST); + + try (ResultSet rs = pstmt.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); + } + } + } } /** @@ -82,15 +82,18 @@ public void testQueryTimestamp() throws SQLException { */ @Test public void testQueryTime() throws SQLException { - String sPrepStmt = "select * from dateandtime where my_time = ?"; - pstmt = connection.prepareStatement(sPrepStmt); - pstmt.setTime(1, TIME_TO_TEST); - - rs = pstmt.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); - rs.close(); - pstmt.close(); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + + String sPrepStmt = "select * from dateandtime where my_time = ?"; + try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { + pstmt.setTime(1, TIME_TO_TEST); + + try (ResultSet rs = pstmt.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); + } + } + } } /** @@ -98,18 +101,22 @@ public void testQueryTime() throws SQLException { */ @Test public void testQueryDateTVP() throws SQLException { - SQLServerDataTable tvp = new SQLServerDataTable(); - tvp.addColumnMetadata("c1", java.sql.Types.DATE); - tvp.addRow(DATE_TO_TEST); - String sPrepStmt = "select * from dateandtime where my_date IN (select * from ?)"; - pstmt = connection.prepareStatement(sPrepStmt); - ((SQLServerPreparedStatement) pstmt).setStructured(1, "dateTVP", tvp); - - rs = pstmt.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); - rs.close(); - pstmt.close(); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + + SQLServerDataTable tvp = new SQLServerDataTable(); + tvp.addColumnMetadata("c1", java.sql.Types.DATE); + tvp.addRow(DATE_TO_TEST); + String sPrepStmt = "select * from dateandtime where my_date IN (select * from ?)"; + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement(sPrepStmt)) { + pstmt.setStructured(1, "dateTVP", tvp); + + try (ResultSet rs = pstmt.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); + } + } + } } /** @@ -117,18 +124,22 @@ public void testQueryDateTVP() throws SQLException { */ @Test public void testQueryTimestampTVP() throws SQLException { - SQLServerDataTable tvp = new SQLServerDataTable(); - tvp.addColumnMetadata("c1", java.sql.Types.TIMESTAMP); - tvp.addRow(TIMESTAMP_TO_TEST); - String sPrepStmt = "select * from dateandtime where my_timestamp IN (select * from ?)"; - pstmt = connection.prepareStatement(sPrepStmt); - ((SQLServerPreparedStatement) pstmt).setStructured(1, "timestampTVP", tvp); - - rs = pstmt.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); - rs.close(); - pstmt.close(); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + + SQLServerDataTable tvp = new SQLServerDataTable(); + tvp.addColumnMetadata("c1", java.sql.Types.TIMESTAMP); + tvp.addRow(TIMESTAMP_TO_TEST); + String sPrepStmt = "select * from dateandtime where my_timestamp IN (select * from ?)"; + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement(sPrepStmt)) { + pstmt.setStructured(1, "timestampTVP", tvp); + + try (ResultSet rs = pstmt.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); + } + } + } } /** @@ -136,25 +147,33 @@ public void testQueryTimestampTVP() throws SQLException { */ @Test public void testQueryTimeTVP() throws SQLException { - SQLServerDataTable tvp = new SQLServerDataTable(); - tvp.addColumnMetadata("c1", java.sql.Types.TIME); - tvp.addRow(TIME_TO_TEST); - String sPrepStmt = "select * from dateandtime where my_time IN (select * from ?)"; - pstmt = connection.prepareStatement(sPrepStmt); - ((SQLServerPreparedStatement) pstmt).setStructured(1, "timeTVP", tvp); - - rs = pstmt.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); - rs.close(); - pstmt.close(); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + + SQLServerDataTable tvp = new SQLServerDataTable(); + tvp.addColumnMetadata("c1", java.sql.Types.TIME); + tvp.addRow(TIME_TO_TEST); + String sPrepStmt = "select * from dateandtime where my_time IN (select * from ?)"; + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement(sPrepStmt)) { + ((SQLServerPreparedStatement) pstmt).setStructured(1, "timeTVP", tvp); + + try (ResultSet rs = pstmt.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 42, "did not find correct timestamp"); + } + } + } } private void createTVPs(String tvpName, String tvpType) throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 " + tvpType + " null)"; - stmt.executeUpdate(TVPCreateCmd); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); + Statement stmt = (SQLServerStatement) connection.createStatement()) { + + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + + "') " + " drop type " + tvpName); + String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 " + tvpType + " null)"; + stmt.executeUpdate(TVPCreateCmd); + } } @BeforeEach @@ -162,44 +181,36 @@ public void testSetup() throws TestAbortedException, Exception { try (DBConnection dbc = new DBConnection(connectionString)) { assumeTrue(9 <= dbc.getServerVersion(), "Aborting test case as SQL Server version does not support TIME"); } + // To get TIME & setTime working on Servers >= 2008, we must add 'sendTimeAsDatetime=false' // by default to the connection. See issue https://github.com/Microsoft/mssql-jdbc/issues/559 - connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); - stmt = (SQLServerStatement) connection.createStatement(); - TestUtils.dropTableIfExists("dateandtime", stmt); - String sql1 = "create table dateandtime (id integer not null, my_date date, my_time time, my_timestamp datetime2 constraint pk_esimple primary key (id))"; - stmt.execute(sql1); - - // add one sample data - String sPrepStmt = "insert into dateandtime (id, my_date, my_time, my_timestamp) values (?, ?, ?, ?)"; - pstmt = connection.prepareStatement(sPrepStmt); - pstmt.setInt(1, 42); - pstmt.setDate(2, DATE_TO_TEST); - pstmt.setTime(3, TIME_TO_TEST); - pstmt.setTimestamp(4, TIMESTAMP_TO_TEST); - pstmt.execute(); - pstmt.close(); - createTVPs("dateTVP", "date"); - createTVPs("timeTVP", "time"); - createTVPs("timestampTVP", "datetime2"); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); + Statement stmt = (SQLServerStatement) connection.createStatement()) { + TestUtils.dropTableIfExists("dateandtime", stmt); + String sql1 = "create table dateandtime (id integer not null, my_date date, my_time time, my_timestamp datetime2 constraint pk_esimple primary key (id))"; + stmt.execute(sql1); + + // add one sample data + String sPrepStmt = "insert into dateandtime (id, my_date, my_time, my_timestamp) values (?, ?, ?, ?)"; + try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { + pstmt.setInt(1, 42); + pstmt.setDate(2, DATE_TO_TEST); + pstmt.setTime(3, TIME_TO_TEST); + pstmt.setTimestamp(4, TIMESTAMP_TO_TEST); + pstmt.execute(); + pstmt.close(); + createTVPs("dateTVP", "date"); + createTVPs("timeTVP", "time"); + createTVPs("timestampTVP", "datetime2"); + } + } } @AfterAll public static void terminateVariation() throws SQLException { - - TestUtils.dropTableIfExists("dateandtime", stmt); - - if (null != connection) { - connection.close(); - } - if (null != pstmt) { - pstmt.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); + try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); + Statement stmt = (SQLServerStatement) connection.createStatement()) { + TestUtils.dropTableIfExists("dateandtime", stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java index 33b76e60e..5672a26c5 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java @@ -12,6 +12,7 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; +import java.sql.Connection; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; @@ -40,13 +41,9 @@ @RunWith(JUnitPlatform.class) public class SQLServerSpatialDatatypeTest extends AbstractTest { - static SQLServerConnection con = null; - static Statement stmt = null; static String geomTableName = "geometryTestTable"; static String geogTableName = "geographyTestTable"; static String spatialDatatypeTableName = "spatialDatatypeTestTable"; - static SQLServerPreparedStatement pstmt = null; - static SQLServerResultSet rs = null; static boolean isDenaliOrLater = false; @Test @@ -304,26 +301,31 @@ public void testCurvePolygonWkt() throws SQLException { @Test public void testFullGlobeWkt() throws SQLException { - if (isDenaliOrLater) { - beforeEachSetup(); - - String geoWKT = "FULLGLOBE"; - Geography geogWKT = Geography.STGeomFromText(geoWKT, 4326); - - try { - Geometry.STGeomFromText(geoWKT, 0); - } catch (SQLServerException e) { - assertEquals(e.getMessage(), "Fullglobe is not supported for Geometry."); - } + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + if (isDenaliOrLater) { + beforeEachSetup(); + + String geoWKT = "FULLGLOBE"; + Geography geogWKT = Geography.STGeomFromText(geoWKT, 4326); + + try { + Geometry.STGeomFromText(geoWKT, 0); + } catch (SQLServerException e) { + assertEquals(e.getMessage(), "Fullglobe is not supported for Geometry."); + } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { - pstmt.setGeography(1, geogWKT); - pstmt.execute(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geogTableName + " values (?)");) { + pstmt.setGeography(1, geogWKT); + pstmt.execute(); - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geogTableName); - rs.next(); - assertEquals(rs.getGeography(1).asTextZM(), geoWKT); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geogTableName)) { + rs.next(); + assertEquals(rs.getGeography(1).asTextZM(), geoWKT); + } + } } } } @@ -474,112 +476,120 @@ public void testAllTypes() throws SQLException { Geography geogWKT; // Geometry - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { - geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTLineString, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTCircularString, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTCompoundCurve, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTCurvePolygon, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTPolygon, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTMultiPoint, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTMultiLineString, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTMultiPolygon, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTGeometryCollection, 0); - pstmt.setGeometry(1, geomWKT); - pstmt.executeUpdate(); - - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geomTableName); - for (int i = 0; i < geoWKTList.size(); i++) { - rs.next(); - assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geomTableName + " values (?)")) { + geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTLineString, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTCircularString, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTCompoundCurve, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTCurvePolygon, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTPolygon, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTMultiPoint, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTMultiLineString, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTMultiPolygon, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTGeometryCollection, 0); + pstmt.setGeometry(1, geomWKT); + pstmt.executeUpdate(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geomTableName)) { + for (int i = 0; i < geoWKTList.size(); i++) { + rs.next(); + assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); + } + } } - } - // Geography - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { - geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); - pstmt.setGeography(1, geogWKT); + // Geography + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geogTableName + " values (?)")) { + geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTLineString, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTLineString, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTCircularString, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTCircularString, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTCompoundCurve, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTCompoundCurve, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTCurvePolygon, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTCurvePolygon, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTPolygon, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTPolygon, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTMultiPoint, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTMultiPoint, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTMultiLineString, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTMultiLineString, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTMultiPolygon, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTMultiPolygon, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - geogWKT = Geography.STGeomFromText(geoWKTGeometryCollection, 4326); - pstmt.setGeography(1, geogWKT); + geogWKT = Geography.STGeomFromText(geoWKTGeometryCollection, 4326); + pstmt.setGeography(1, geogWKT); - pstmt.executeUpdate(); + pstmt.executeUpdate(); - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geogTableName); - for (int i = 0; i < geoWKTList.size(); i++) { - rs.next(); - assertEquals(rs.getGeography(1).asTextZM(), geoWKTList.get(i)); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geogTableName)) { + for (int i = 0; i < geoWKTList.size(); i++) { + rs.next(); + assertEquals(rs.getGeography(1).asTextZM(), geoWKTList.get(i)); + } + } } } } @@ -621,116 +631,121 @@ public void testMixedAllTypes() throws SQLException { Geometry geomWKT; Geography geogWKT; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { - geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); - geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTLineString, 0); - geogWKT = Geography.STGeomFromText(geoWKTLineString, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTCircularString, 0); - geogWKT = Geography.STGeomFromText(geoWKTCircularString, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTCompoundCurve, 0); - geogWKT = Geography.STGeomFromText(geoWKTCompoundCurve, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTCurvePolygon, 0); - geogWKT = Geography.STGeomFromText(geoWKTCurvePolygon, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTPolygon, 0); - geogWKT = Geography.STGeomFromText(geoWKTPolygon, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTMultiPoint, 0); - geogWKT = Geography.STGeomFromText(geoWKTMultiPoint, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTMultiLineString, 0); - geogWKT = Geography.STGeomFromText(geoWKTMultiLineString, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTMultiPolygon, 0); - geogWKT = Geography.STGeomFromText(geoWKTMultiPolygon, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTGeometryCollection, 0); - geogWKT = Geography.STGeomFromText(geoWKTGeometryCollection, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - rs = (SQLServerResultSet) stmt.executeQuery("select * from " + spatialDatatypeTableName); - for (int i = 0; i < geoWKTList.size(); i++) { - rs.next(); - assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); - assertEquals(rs.getGeography(2).asTextZM(), geoWKTList.get(i)); - assertEquals(rs.getString(3), s); - assertEquals((Double) rs.getDouble(4), d); - assertEquals(rs.getInt(5), i2); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { + geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); + geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTLineString, 0); + geogWKT = Geography.STGeomFromText(geoWKTLineString, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTCircularString, 0); + geogWKT = Geography.STGeomFromText(geoWKTCircularString, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTCompoundCurve, 0); + geogWKT = Geography.STGeomFromText(geoWKTCompoundCurve, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTCurvePolygon, 0); + geogWKT = Geography.STGeomFromText(geoWKTCurvePolygon, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTPolygon, 0); + geogWKT = Geography.STGeomFromText(geoWKTPolygon, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTMultiPoint, 0); + geogWKT = Geography.STGeomFromText(geoWKTMultiPoint, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTMultiLineString, 0); + geogWKT = Geography.STGeomFromText(geoWKTMultiLineString, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTMultiPolygon, 0); + geogWKT = Geography.STGeomFromText(geoWKTMultiPolygon, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTGeometryCollection, 0); + geogWKT = Geography.STGeomFromText(geoWKTGeometryCollection, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + spatialDatatypeTableName)) { + for (int i = 0; i < geoWKTList.size(); i++) { + rs.next(); + assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); + assertEquals(rs.getGeography(2).asTextZM(), geoWKTList.get(i)); + assertEquals(rs.getString(3), s); + assertEquals((Double) rs.getDouble(4), d); + assertEquals(rs.getInt(5), i2); + } + } } } } @@ -755,27 +770,36 @@ public void testParse() throws SQLException { Geometry geomWKT = Geometry.parse(geoWKT); Geography geogWKT = Geography.parse(geoWKT); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { - pstmt.setGeometry(1, geomWKT); - pstmt.execute(); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geomTableName); - rs.next(); - assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); - assertEquals(rs.getGeometry(1).getSrid(), 0); - } + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geomTableName + " values (?)");) { + pstmt.setGeometry(1, geomWKT); + pstmt.execute(); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { - pstmt.setGeography(1, geogWKT); - pstmt.execute(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geomTableName)) { + rs.next(); + assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); + assertEquals(rs.getGeometry(1).getSrid(), 0); + } + } - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geogTableName); - rs.next(); - assertEquals(rs.getGeography(1).asTextZM(), geoWKT); - assertEquals(rs.getGeography(1).getSrid(), 4326); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geogTableName + " values (?)");) { + pstmt.setGeography(1, geogWKT); + pstmt.execute(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geogTableName)) { + rs.next(); + assertEquals(rs.getGeography(1).asTextZM(), geoWKT); + assertEquals(rs.getGeography(1).getSrid(), 4326); + } + } } + } @Test @@ -787,26 +811,34 @@ public void testPoint() throws SQLException { Geometry geomWKT = Geometry.point(1, 2, 0); Geography geogWKT = Geography.point(1, 2, 4326); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { - pstmt.setGeometry(1, geomWKT); - pstmt.execute(); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geomTableName); - rs.next(); - assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); - assertEquals(rs.getGeometry(1).getSrid(), 0); - } + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geomTableName + " values (?)");) { + pstmt.setGeometry(1, geomWKT); + pstmt.execute(); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { - pstmt.setGeography(1, geogWKT); - pstmt.execute(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geomTableName)) { + rs.next(); + assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); + assertEquals(rs.getGeometry(1).getSrid(), 0); + } + } - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geogTableName); - rs.next(); - assertEquals(rs.getGeography(1).asTextZM(), geoWKT); - assertEquals(rs.getGeography(1).getSrid(), 4326); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geogTableName + " values (?)");) { + pstmt.setGeography(1, geogWKT); + pstmt.execute(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geogTableName)) { + rs.next(); + assertEquals(rs.getGeography(1).asTextZM(), geoWKT); + assertEquals(rs.getGeography(1).getSrid(), 4326); + } + } } } @@ -820,24 +852,32 @@ public void testSTAsText() throws SQLException { Geometry geomWKT = Geometry.STGeomFromText(geoWKT, 0); Geography geogWKT = Geography.STGeomFromText(geoWKT, 4326); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { - pstmt.setGeometry(1, geomWKT); - pstmt.execute(); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geomTableName); - rs.next(); - assertEquals(rs.getGeometry(1).STAsText(), geoWKTSS); - } + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geomTableName + " values (?)");) { + pstmt.setGeometry(1, geomWKT); + pstmt.execute(); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { - pstmt.setGeography(1, geogWKT); - pstmt.execute(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geomTableName)) { + rs.next(); + assertEquals(rs.getGeometry(1).STAsText(), geoWKTSS); + } + } - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geogTableName); - rs.next(); - assertEquals(rs.getGeography(1).STAsText(), geoWKTSS); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geogTableName + " values (?)");) { + pstmt.setGeography(1, geogWKT); + pstmt.execute(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geogTableName)) { + rs.next(); + assertEquals(rs.getGeography(1).STAsText(), geoWKTSS); + } + } } } @@ -867,8 +907,10 @@ public void testSTAsBinary() throws SQLException { public void testCheckGeomMetaData() throws SQLException { beforeEachSetup(); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + geomTableName + " (c1) VALUES (?)");) { + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + geomTableName + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); Geometry g = Geometry.STGeomFromText("POINT (1 2 3 4)", 0); pstmt.setGeometry(1, g); @@ -888,8 +930,10 @@ public void testCheckGeomMetaData() throws SQLException { public void testCheckGeogMetaData() throws SQLException { beforeEachSetup(); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + geogTableName + " (c1) VALUES (?)");) { + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + geogTableName + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); Geography g = Geography.STGeomFromText("POINT (1 2 3 4)", 4326); pstmt.setGeography(1, g); @@ -949,52 +993,64 @@ public void testNull() throws SQLException { Geometry geomWKT; Geography geogWKT; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { - geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); - geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - geomWKT = Geometry.STGeomFromText(geoWKTLineString, 0); - geogWKT = Geography.STGeomFromText(geoWKTLineString, 4326); - pstmt.setGeometry(1, geomWKT); - pstmt.setGeography(2, geogWKT); - pstmt.setString(3, s); - pstmt.setDouble(4, d); - pstmt.setInt(5, i2); - - pstmt.executeUpdate(); - - rs = (SQLServerResultSet) stmt.executeQuery("select * from " + spatialDatatypeTableName); - for (int i = 0; i < geoWKTList.size(); i++) { - rs.next(); - assertEquals(rs.getGeometry(1).asTextZM(), geoWKTListExpected.get(i)); - assertEquals(rs.getGeography(2).asTextZM(), geoWKTListExpected.get(i)); - assertEquals(rs.getString(3), s); - assertEquals((Double) rs.getDouble(4), d); - assertEquals(rs.getInt(5), i2); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { + geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); + geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + geomWKT = Geometry.STGeomFromText(geoWKTLineString, 0); + geogWKT = Geography.STGeomFromText(geoWKTLineString, 4326); + pstmt.setGeometry(1, geomWKT); + pstmt.setGeography(2, geogWKT); + pstmt.setString(3, s); + pstmt.setDouble(4, d); + pstmt.setInt(5, i2); + + pstmt.executeUpdate(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + spatialDatatypeTableName)) { + for (int i = 0; i < geoWKTList.size(); i++) { + rs.next(); + assertEquals(rs.getGeometry(1).asTextZM(), geoWKTListExpected.get(i)); + assertEquals(rs.getGeography(2).asTextZM(), geoWKTListExpected.get(i)); + assertEquals(rs.getString(3), s); + assertEquals((Double) rs.getDouble(4), d); + assertEquals(rs.getInt(5), i2); + } + } } } } } private void beforeEachSetup() throws SQLException { - TestUtils.dropTableIfExists(geomTableName, stmt); - TestUtils.dropTableIfExists(geogTableName, stmt); - stmt.executeUpdate("Create table " + geomTableName + " (c1 geometry)"); - stmt.executeUpdate("Create table " + geogTableName + " (c1 geography)"); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(geomTableName, stmt); + TestUtils.dropTableIfExists(geogTableName, stmt); + stmt.executeUpdate("Create table " + geomTableName + " (c1 geometry)"); + stmt.executeUpdate("Create table " + geogTableName + " (c1 geography)"); + } } private void beforeEachSetupSpatialDatatype() throws SQLException { - TestUtils.dropTableIfExists(spatialDatatypeTableName, stmt); - stmt.executeUpdate("Create table " + spatialDatatypeTableName + " (c1 geometry," + "c2 geography," - + "c3 nvarchar(512)," + "c4 decimal(28,4)," + "c5 int)"); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(spatialDatatypeTableName, stmt); + stmt.executeUpdate("Create table " + spatialDatatypeTableName + " (c1 geometry," + "c2 geography," + + "c3 nvarchar(512)," + "c4 decimal(28,4)," + "c5 int)"); + } } private void testWkt(String geoWKT) throws SQLException { @@ -1005,24 +1061,32 @@ private void testWkt(String geoWKT, String geoWKTSS) throws SQLException { Geometry geomWKT = Geometry.STGeomFromText(geoWKT, 0); Geography geogWKT = Geography.STGeomFromText(geoWKT, 4326); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { - pstmt.setGeometry(1, geomWKT); - pstmt.execute(); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geomTableName); - rs.next(); - assertEquals(rs.getGeometry(1).asTextZM(), geoWKTSS); - } + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geomTableName + " values (?)");) { + pstmt.setGeometry(1, geomWKT); + pstmt.execute(); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { - pstmt.setGeography(1, geogWKT); - pstmt.execute(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geomTableName)) { + rs.next(); + assertEquals(rs.getGeometry(1).asTextZM(), geoWKTSS); + } + } - rs = (SQLServerResultSet) stmt.executeQuery("select c1 from " + geogTableName); - rs.next(); - assertEquals(rs.getGeography(1).asTextZM(), geoWKTSS); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement("insert into " + geogTableName + " values (?)");) { + pstmt.setGeography(1, geogWKT); + pstmt.execute(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select c1 from " + geogTableName)) { + rs.next(); + assertEquals(rs.getGeography(1).asTextZM(), geoWKTSS); + } + } } } @@ -1045,22 +1109,22 @@ private static byte[] hexStringToByteArray(String s) { */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { - con = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = con.createStatement(); - - rs = (SQLServerResultSet) stmt.executeQuery("select SERVERPROPERTY ( 'ProductVersion' )"); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select SERVERPROPERTY ( 'ProductVersion' )")) { - rs.next(); + rs.next(); - try { - int version = Integer.parseInt(rs.getString(1).substring(0, 2)); + try { + int version = Integer.parseInt(rs.getString(1).substring(0, 2)); - // if major version is greater than or equal to 11, it's SQL Server 2012 or above. - if (version >= 11) { - isDenaliOrLater = true; + // if major version is greater than or equal to 11, it's SQL Server 2012 or above. + if (version >= 11) { + isDenaliOrLater = true; + } + } catch (Exception e) { + // Do nothing. } - } catch (Exception e) { - // Do nothing. } } @@ -1071,23 +1135,10 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(geomTableName, stmt); TestUtils.dropTableIfExists(geogTableName, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != pstmt) { - pstmt.close(); - } - - if (null != rs) { - rs.close(); - } - - if (null != con) { - con.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 b5aaaf964..020ce57e2 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -39,12 +39,10 @@ public class TVPWithSqlVariantTest extends AbstractTest { private static SQLServerConnection conn = null; static SQLServerStatement stmt = null; - static SQLServerResultSet rs = null; static SQLServerDataTable tvp = null; private static String tvpName = "numericTVP"; private static String destTable = "destTvpSqlVariantTable"; private static String procedureName = "procedureThatCallsTVP"; - static SQLServerPreparedStatement pstmt = null; /** * Test a previous failure regarding to numeric precision. Issue #211 @@ -57,19 +55,19 @@ public void testInt() throws SQLException { tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(12); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getInt(1), 12); - assertEquals(rs.getString(1), "" + 12); - assertEquals(rs.getObject(1), 12); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getInt(1), 12); + assertEquals(rs.getString(1), "" + 12); + assertEquals(rs.getObject(1), 12); + } } } @@ -86,16 +84,16 @@ public void testDate() throws SQLException { tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(date); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getString(1), "" + date); // TODO: GetDate has issues + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), "" + date); // TODO: GetDate has issues + } } } @@ -111,16 +109,16 @@ public void testMoney() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(new BigDecimal(numeric[14])); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getMoney(1), new BigDecimal(numeric[14])); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getMoney(1), new BigDecimal(numeric[14])); + } } } @@ -136,19 +134,20 @@ public void testSmallInt() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Short.valueOf(numeric[2])); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); - if (null != pstmt) { - pstmt.close(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals("" + rs.getInt(1), numeric[2]); - // System.out.println(rs.getShort(1)); //does not work says cannot cast integer to short cause it is written - // as int + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals("" + rs.getInt(1), numeric[2]); + // System.out.println(rs.getShort(1)); //does not work says cannot cast integer to short cause it is + // written + // as int + } } } @@ -165,16 +164,15 @@ public void testBigInt() throws SQLException { String[] numeric = createNumericValues(); tvp.addRow(Long.parseLong(numeric[4])); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getLong(1), Long.parseLong(numeric[4])); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getLong(1), Long.parseLong(numeric[4])); + } } } @@ -190,16 +188,15 @@ public void testBoolean() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Boolean.parseBoolean(numeric[0])); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getBoolean(1), Boolean.parseBoolean(numeric[0])); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getBoolean(1), Boolean.parseBoolean(numeric[0])); + } } } @@ -215,16 +212,15 @@ public void testFloat() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Float.parseFloat(numeric[1])); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getFloat(1), Float.parseFloat(numeric[1])); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getFloat(1), Float.parseFloat(numeric[1])); + } } } @@ -240,16 +236,15 @@ public void testNvarChar() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String colValue = "س"; tvp.addRow(colValue); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getString(1), colValue); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), colValue); + } } } @@ -270,16 +265,15 @@ public void testVarChar8000() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } } } @@ -300,20 +294,17 @@ public void testLongVarChar() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - try { - pstmt.execute(); - } catch (SQLException e) { - assertTrue( - e.getMessage().contains("SQL_VARIANT does not support string values of length greater than 8000.")); - } catch (Exception e) { - // Test should have failed! mistakenly inserted string value of more than 8000 in sql-variant - fail(TestResource.getResource("R_unexpectedException")); - } finally { - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + try { + pstmt.execute(); + } catch (SQLException e) { + assertTrue(e.getMessage() + .contains("SQL_VARIANT does not support string values of length greater than 8000.")); + } catch (Exception e) { + // Test should have failed! mistakenly inserted string value of more than 8000 in sql-variant + fail(TestResource.getResource("R_unexpectedException")); } } } @@ -331,17 +322,16 @@ public void testDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(timestamp); - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - assertEquals(rs.getString(1), "" + timestamp); - // System.out.println(rs.getDateTime(1));// TODO does not work + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), "" + timestamp); + // System.out.println(rs.getDateTime(1));// TODO does not work + } } } @@ -361,16 +351,15 @@ public void testNull() throws SQLException { assertTrue(e.getMessage().startsWith("Use of TVPs containing null sql_variant columns is not supported.")); } - pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - pstmt.execute(); - if (null != pstmt) { - pstmt.close(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); + pstmt.execute(); } - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable); - while (rs.next()) { - System.out.println(rs.getString(1)); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + while (rs.next()) { + System.out.println(rs.getString(1)); + } } } @@ -390,12 +379,13 @@ public void testIntStoredProcedure() throws SQLException { SQLServerCallableStatement Cstatement = (SQLServerCallableStatement) conn.prepareCall(sql); Cstatement.setStructured(1, tvpName, tvp); Cstatement.execute(); - rs = (SQLServerResultSet) stmt.executeQuery("select * from " + destTable); - while (rs.next()) { - System.out.println(rs.getString(1)); - } - if (null != Cstatement) { - Cstatement.close(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + destTable)) { + while (rs.next()) { + System.out.println(rs.getString(1)); + } + if (null != Cstatement) { + Cstatement.close(); + } } } @@ -518,14 +508,6 @@ public static void afterAll() throws SQLException { stmt.close(); } - if (null != pstmt) { - pstmt.close(); - } - - if (null != rs) { - rs.close(); - } - if (null != conn) { conn.close(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java index 01bcebb0b..b5e2df033 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java @@ -10,6 +10,8 @@ import java.net.SocketTimeoutException; import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.Connection; +import java.sql.Statement; import java.text.MessageFormat; import org.junit.jupiter.api.Test; @@ -62,33 +64,25 @@ public void testBulkCSVFileRecordExceptionCause() throws Exception { */ @Test public void testSocketTimeoutExceptionCause() throws Exception { - SQLServerConnection conn = null; - try { - conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - - TestUtils.dropProcedureIfExists(waitForDelaySPName, conn.createStatement()); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + TestUtils.dropProcedureIfExists(waitForDelaySPName, stmt); createWaitForDelayPreocedure(conn); - - conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); - - try { - conn.createStatement().execute("exec " + waitForDelaySPName); - throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (Exception e) { - if (!(e instanceof SQLException)) { - throw e; - } - - assertTrue(null != e.getCause(), TestResource.getResource("R_causeShouldNotBeNull")); - MessageFormat form = new MessageFormat(TestResource.getResource("R_causeShouldBeInstance")); - Object[] msgArgs = {"SocketTimeoutException"}; - assertTrue(e.getCause() instanceof SocketTimeoutException, form.format(msgArgs)); - } - } finally { - if (null != conn) { - conn.close(); + } + try (Connection conn = DriverManager + .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); + Statement stmt = conn.createStatement()) { + stmt.execute("exec " + waitForDelaySPName); + throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (Exception e) { + if (!(e instanceof SQLException)) { + throw e; } + + assertTrue(null != e.getCause(), TestResource.getResource("R_causeShouldNotBeNull")); + MessageFormat form = new MessageFormat(TestResource.getResource("R_causeShouldBeInstance")); + Object[] msgArgs = {"SocketTimeoutException"}; + assertTrue(e.getCause() instanceof SocketTimeoutException, form.format(msgArgs)); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java index 0d5422458..8eae8958a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java @@ -163,7 +163,6 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } Statement stmt = con.createStatement(); - ResultSet rs = null; TestUtils.dropTableIfExists("TEST_TABLE", stmt); con.setAutoCommit(false); @@ -228,8 +227,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { Map selectedValues = new LinkedHashMap<>(); int id = 0; try (PreparedStatement pstmt = con.prepareStatement("select * from TEST_TABLE;")) { - try { - rs = pstmt.executeQuery(); + try (ResultSet rs = pstmt.executeQuery()) { int i = 0; while (rs.next()) { id = rs.getInt(1); @@ -240,10 +238,6 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } selectedValues.put(id, data); } - } finally { - if (null != rs) { - rs.close(); - } } } finally { TestUtils.dropTableIfExists("TEST_TABLE", stmt); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java index c004db9c0..fb74cde68 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java @@ -17,7 +17,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; @@ -32,9 +31,6 @@ @RunWith(JUnitPlatform.class) public class TVPResultSetCursorTest 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"}; @@ -65,25 +61,25 @@ public void testServerCursors() throws SQLException { } private void serverCursorsTest(int resultSetType, int resultSetConcurrency) throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - dropTVPS(); - dropTables(); + dropTVPS(); + dropTables(); - createTVPS(); - createTables(); + createTVPS(); + createTables(); - populateSourceTable(); + populateSourceTable(); - try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency) - .executeQuery("select * from " + srcTable); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); - pstmt.execute(); + try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency) + .executeQuery("select * from " + srcTable); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); - verifyDestinationTableData(expectedBigDecimals.length); + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -97,25 +93,25 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro public void testSelectMethodSetToCursor() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = DriverManager.getConnection(connectionString, info); + Statement stmt = conn.createStatement()) { - stmt = conn.createStatement(); + dropTVPS(); + dropTables(); - dropTVPS(); - dropTables(); + createTVPS(); + createTables(); - createTVPS(); - createTables(); + populateSourceTable(); - populateSourceTable(); - - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); - pstmt.execute(); + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); - verifyDestinationTableData(expectedBigDecimals.length); + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -129,30 +125,30 @@ public void testSelectMethodSetToCursor() throws SQLException { public void testSelectMethodSetToCursorWithSP() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = DriverManager.getConnection(connectionString, info); + Statement stmt = conn.createStatement()) { - stmt = conn.createStatement(); - - dropProcedure(); - dropTVPS(); - dropTables(); + dropProcedure(); + dropTVPS(); + dropTables(); - createTVPS(); - createTables(); - createPreocedure(); + createTVPS(); + createTables(); + createPreocedure(); - populateSourceTable(); + populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn - .prepareCall("{call " + procedureName + "(?)}")) { - pstmt.setStructured(1, tvpName, rs); + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn + .prepareCall("{call " + procedureName + "(?)}")) { + pstmt.setStructured(1, tvpName, rs); - pstmt.execute(); + pstmt.execute(); - verifyDestinationTableData(expectedBigDecimals.length); - } finally { - dropProcedure(); + verifyDestinationTableData(expectedBigDecimals.length); + } finally { + dropProcedure(); + } } } @@ -165,28 +161,28 @@ public void testSelectMethodSetToCursorWithSP() throws SQLException { public void testInvalidTVPName() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - conn = DriverManager.getConnection(connectionString, info); - - stmt = conn.createStatement(); + try (Connection conn = DriverManager.getConnection(connectionString, info); + Statement stmt = conn.createStatement()) { - dropTVPS(); - dropTables(); + dropTVPS(); + dropTables(); - createTVPS(); - createTables(); + createTVPS(); + createTables(); - populateSourceTable(); + populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, "invalid" + tvpName, rs); + pstmt.setStructured(1, "invalid" + tvpName, rs); - pstmt.execute(); - } catch (SQLException e) { - if (!e.getMessage().contains(TestResource.getResource("R_dataTypeNotFound"))) { - throw e; + pstmt.execute(); + } catch (SQLException e) { + if (!e.getMessage().contains(TestResource.getResource("R_dataTypeNotFound"))) { + throw e; + } } } } @@ -200,33 +196,33 @@ public void testInvalidTVPName() throws SQLException { public void testInvalidStoredProcedureName() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = DriverManager.getConnection(connectionString, info); + Statement stmt = conn.createStatement()) { - stmt = conn.createStatement(); + dropProcedure(); + dropTVPS(); + dropTables(); - dropProcedure(); - dropTVPS(); - dropTables(); + createTVPS(); + createTables(); + createPreocedure(); - createTVPS(); - createTables(); - createPreocedure(); + populateSourceTable(); - populateSourceTable(); + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn + .prepareCall("{call invalid" + procedureName + "(?)}")) { + pstmt.setStructured(1, tvpName, rs); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn - .prepareCall("{call invalid" + procedureName + "(?)}")) { - pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); + } catch (SQLException e) { + if (!e.getMessage().contains(TestResource.getResource("R_StoredProcedureNotFound"))) { + throw e; + } + } finally { - pstmt.execute(); - } catch (SQLException e) { - if (!e.getMessage().contains(TestResource.getResource("R_StoredProcedureNotFound"))) { - throw e; + dropProcedure(); } - } finally { - - dropProcedure(); } } @@ -237,88 +233,71 @@ public void testInvalidStoredProcedureName() throws SQLException { */ @Test public void testMultiplePreparedStatementAndResultSet() throws SQLException { - conn = DriverManager.getConnection(connectionString); - - stmt = conn.createStatement(); - - dropTVPS(); - dropTables(); - - createTVPS(); - createTables(); - - populateSourceTable(); - - ResultSet rs = null; - ResultSet rs2 = null; - SQLServerPreparedStatement pstmt1 = null; - SQLServerPreparedStatement pstmt2 = null; - - try { - - rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) - .executeQuery("select * from " + srcTable); - - pstmt1 = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt1.setStructured(1, tvpName, rs); - pstmt1.execute(); - verifyDestinationTableData(expectedBigDecimals.length); - - rs.beforeFirst(); - pstmt1 = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt1.setStructured(1, tvpName, rs); - pstmt1.execute(); - verifyDestinationTableData(expectedBigDecimals.length * 2); - - rs.beforeFirst(); - pstmt2 = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt2.setStructured(1, tvpName, rs); - pstmt2.execute(); - verifyDestinationTableData(expectedBigDecimals.length * 3); - - String sql = "insert into " + desTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - 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); - - rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) - .executeQuery("select * from " + srcTable); - - pstmt1 = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;"); - pstmt1.setStructured(1, tvpName, rs2); - pstmt1.execute(); - verifyDestinationTableData(expectedBigDecimals.length * 5); - } finally { - - if (null != pstmt1) { - pstmt1.close(); - } - if (null != pstmt2) { - pstmt2.close(); - } - if (null != rs) { - rs.close(); - } - - if (null != rs2) { - rs2.close(); + try (Connection conn = DriverManager.getConnection(connectionString)) { + + dropTVPS(); + dropTables(); + + createTVPS(); + createTables(); + + populateSourceTable(); + + try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + try (ResultSet rs = stmt.executeQuery("select * from " + srcTable)) { + + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); + verifyDestinationTableData(expectedBigDecimals.length); + + rs.beforeFirst(); + } + + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); + verifyDestinationTableData(expectedBigDecimals.length * 2); + + rs.beforeFirst(); + } + + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); + verifyDestinationTableData(expectedBigDecimals.length * 3); + } + + String sql = "insert into " + desTable + " values (?,?,?,?)"; + Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + try (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(); + } + verifyDestinationTableData(expectedBigDecimals.length * 4); + } + } + try (ResultSet rs = stmt.executeQuery("select * from " + srcTable); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, rs); + pstmt.execute(); + verifyDestinationTableData(expectedBigDecimals.length * 5); + } } } } private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { int expectedArrayLength = expectedBigDecimals.length; @@ -344,7 +323,8 @@ private static void populateSourceTable() throws SQLException { Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { for (int i = 0; i < expectedBigDecimals.length; i++) { pstmt.setBigDecimal(1, expectedBigDecimals[i]); @@ -357,50 +337,51 @@ private static void populateSourceTable() throws SQLException { } private static void dropTables() throws SQLException { - TestUtils.dropTableIfExists(srcTable, stmt); - TestUtils.dropTableIfExists(desTable, stmt); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + TestUtils.dropTableIfExists(srcTable, stmt); + TestUtils.dropTableIfExists(desTable, stmt); + } } private static void createTables() 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); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + 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); + } } private static void createTVPS() throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + tvpName - + " as table (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000) null)"; - stmt.execute(TVPCreateCmd); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + String TVPCreateCmd = "CREATE TYPE " + tvpName + + " as table (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000) null)"; + stmt.execute(TVPCreateCmd); + } } private static void dropTVPS() throws SQLException { - stmt.execute("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " + + " drop type " + tvpName); + } } private static void dropProcedure() throws SQLException { - TestUtils.dropProcedureIfExists(procedureName, stmt); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + TestUtils.dropProcedureIfExists(procedureName, stmt); + } } private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + desTable + " SELECT * FROM @InputData" + " END"; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + + " BEGIN " + " INSERT INTO " + desTable + " SELECT * FROM @InputData" + " END"; stmt.execute(sql); - } - - @AfterEach - public void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java index a187fd64f..260c13974 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java @@ -31,9 +31,6 @@ @RunWith(JUnitPlatform.class) public class TVPTypesTest extends AbstractTest { - private static Connection conn = null; - static Statement stmt = null; - static ResultSet rs = null; static SQLServerDataTable tvp = null; private static String tvpName = "TVP"; private static String table = "TVPTable"; @@ -65,9 +62,11 @@ public void testLongVarchar() throws SQLException { pstmt.execute(); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } } } } @@ -97,9 +96,12 @@ public void testLongNVarchar() throws SQLException { pstmt.execute(); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } } } } @@ -127,10 +129,11 @@ public void testXML() throws SQLException { pstmt.execute(); - Connection con = DriverManager.getConnection(connectionString); - ResultSet rs = con.createStatement().executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -157,10 +160,11 @@ public void testnText() throws SQLException { pstmt.execute(); - Connection con = DriverManager.getConnection(connectionString); - ResultSet rs = con.createStatement().executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -187,10 +191,11 @@ public void testText() throws SQLException { pstmt.execute(); - Connection con = DriverManager.getConnection(connectionString); - ResultSet rs = con.createStatement().executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -211,20 +216,18 @@ public void testImage() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARBINARY); tvp.addRow(value.getBytes()); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;"); - pstmt.setStructured(1, tvpName, tvp); - - pstmt.execute(); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection + .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + pstmt.setStructured(1, tvpName, tvp); - Connection con = DriverManager.getConnection(connectionString); - ResultSet rs = con.createStatement().executeQuery("select * from " + table); + pstmt.execute(); - while (rs.next()) - assertTrue(parseByte(rs.getBytes(1), value.getBytes())); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { - if (null != pstmt) { - pstmt.close(); + while (rs.next()) + assertTrue(parseByte(rs.getBytes(1), value.getBytes())); + } } } @@ -254,9 +257,11 @@ public void testTVPLongVarcharStoredProcedure() throws SQLException { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -285,9 +290,11 @@ public void testTVPLongNVarcharStoredProcedure() throws SQLException { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -316,9 +323,11 @@ public void testTVPXMLStoredProcedure() throws SQLException { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -348,9 +357,11 @@ public void testTVPTextStoredProcedure() throws SQLException { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -380,9 +391,11 @@ public void testTVPNTextStoredProcedure() throws SQLException { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertEquals(rs.getString(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertEquals(rs.getString(1), value); + } } } @@ -412,9 +425,11 @@ public void testTVPImageStoredProcedure() throws SQLException { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + table); - while (rs.next()) - assertTrue(parseByte(rs.getBytes(1), value.getBytes())); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) + assertTrue(parseByte(rs.getBytes(1), value.getBytes())); + } } } @@ -440,9 +455,11 @@ public void testDateTime() throws SQLException { pstmt.execute(); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(((SQLServerResultSet) rs).getDateTime(1), value); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) { + assertEquals(((SQLServerResultSet) rs).getDateTime(1), value); + } } } } @@ -470,62 +487,74 @@ public void testSmallDateTime() throws SQLException { pstmt.execute(); - rs = conn.createStatement().executeQuery("select * from " + table); - while (rs.next()) { - assertEquals(((SQLServerResultSet) rs).getSmallDateTime(1), returnValue); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + table)) { + while (rs.next()) { + assertEquals(((SQLServerResultSet) rs).getSmallDateTime(1), returnValue); + } } } } @BeforeEach public void testSetup() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - - dropProcedure(); - dropTables(); - dropTVPS(); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + dropProcedure(); + dropTables(); + dropTVPS(); + } } @AfterAll public static void terminate() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - dropProcedure(); - dropTables(); - dropTVPS(); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + dropProcedure(); + dropTables(); + dropTVPS(); + } } private static void dropProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + procedureName - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + procedureName; - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + procedureName + + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + procedureName; + stmt.execute(sql); + } } private static void dropTables() throws SQLException { - stmt.executeUpdate("if object_id('" + table + "','U') is not null" + " drop table " + table); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("if object_id('" + table + "','U') is not null" + " drop table " + table); + } } private static void dropTVPS() throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + + "') " + " drop type " + tvpName); + } } private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + table + " SELECT * FROM @InputData" + " END"; - - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + + " BEGIN " + " INSERT INTO " + table + " SELECT * FROM @InputData" + " END"; + stmt.execute(sql); + } } private void createTables(String colType) throws SQLException { - String sql = "create table " + table + " (c1 " + colType + " null);"; - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + String sql = "create table " + table + " (c1 " + colType + " null);"; + stmt.execute(sql); + } } private void createTVPS(String colType) throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 " + colType + " null)"; - stmt.executeUpdate(TVPCreateCmd); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 " + colType + " null)"; + stmt.executeUpdate(TVPCreateCmd); + } } private boolean parseByte(byte[] expectedData, byte[] retrieved) { @@ -539,15 +568,6 @@ private boolean parseByte(byte[] expectedData, byte[] retrieved) { @AfterEach public void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } if (null != tvp) { tvp.clear(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java index 10dd7472c..49589800f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java @@ -149,7 +149,6 @@ public void clearTable() throws SQLException { } public void validate(String value) throws SQLException { - ResultSet rs = null; try (PreparedStatement psInsert = connection.prepareStatement("INSERT INTO " + tableName + " VALUES(?)"); PreparedStatement psFetch = connection.prepareStatement("SELECT * FROM " + tableName); Statement stmt = connection.createStatement();) { @@ -161,23 +160,20 @@ public void validate(String value) throws SQLException { psInsert.executeUpdate(); // Fetch using Statement. - rs = stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - // Compare Strings. - assertEquals(value, rs.getString(1)); - // Test UTF8 sequence returned from getBytes(). - assertArrayEquals(valueBytes, rs.getBytes(1)); - + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + rs.next(); + // Compare Strings. + assertEquals(value, rs.getString(1)); + // Test UTF8 sequence returned from getBytes(). + assertArrayEquals(valueBytes, rs.getBytes(1)); + } + // Fetch using PreparedStatement. try (ResultSet rsPreparedStatement = psFetch.executeQuery()) { rsPreparedStatement.next(); assertEquals(value, rsPreparedStatement.getString(1)); assertArrayEquals(valueBytes, rsPreparedStatement.getBytes(1)); } - } finally { - if (null != rs) { - rs.close(); - } } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java index 264f2fa36..9a70e4390 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java @@ -97,13 +97,14 @@ private void testExecuteBatch1Internal(String mode) { pstmt.setInt(1, 3); pstmt.addBatch(); - + int[] updateCount = pstmt.executeBatch(); + updateCountlen = updateCount.length; assertTrue(updateCountlen == 3, TestResource.getResource("R_executeBatchFailed") + ": " + TestResource.getResource("R_incorrectUpdateCount")); - + String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1)) { 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 cd9bd0a2e..d053fd8f9 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 @@ -46,41 +46,37 @@ public class PoolableTest extends AbstractTest { 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: " + TestResource.getResource("R_incorrectDefault")); + // First get the default values + boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); + assertEquals(isPoolable, false, "SQLServerStatement: " + TestResource.getResource("R_incorrectDefault")); - try (PreparedStatement prepStmt = connection.prepareStatement("select 1")) { - isPoolable = ((SQLServerPreparedStatement) prepStmt).isPoolable(); - assertEquals(isPoolable, true, - "SQLServerPreparedStatement: " + TestResource.getResource("R_incorrectDefault")); - } - - try (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: " + TestResource.getResource("R_incorrectDefault")); + } - assertEquals(isPoolable, true, - "SQLServerCallableStatement: " + TestResource.getResource("R_incorrectDefault")); + try (CallableStatement callableStatement = connection + .prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }");) { + isPoolable = ((SQLServerCallableStatement) callableStatement).isPoolable(); - // Now do couple of sets and gets + assertEquals(isPoolable, true, + "SQLServerCallableStatement: " + TestResource.getResource("R_incorrectDefault")); - ((SQLServerCallableStatement) callableStatement).setPoolable(false); - assertEquals(((SQLServerCallableStatement) callableStatement).isPoolable(), false, - "set did not work"); - } + // Now do couple of sets and gets - ((SQLServerStatement) statement).setPoolable(true); - assertEquals(((SQLServerStatement) statement).isPoolable(), true, "set did not work"); - } catch (UnsupportedOperationException e) { - // PoolableTest should be supported in anything other than 1.5 - assertEquals(System.getProperty("java.specification.version"), "1.5", - "PoolableTest " + TestResource.getResource("R_shouldBeSupported")); - assertEquals(e.getMessage(), TestResource.getResource("R_operationNotSupported")); - assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedExceptionContent")); + ((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) { + // PoolableTest should be supported in anything other than 1.5 + assertEquals(System.getProperty("java.specification.version"), "1.5", + "PoolableTest " + TestResource.getResource("R_shouldBeSupported")); + assertEquals(e.getMessage(), TestResource.getResource("R_operationNotSupported")); + assertEquals(e.getMessage(), TestResource.getResource("R_unexpectedExceptionContent")); } } @@ -92,12 +88,9 @@ public void poolableTest() throws SQLException, ClassNotFoundException { @AfterAll public static void afterAll() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - try { - TestUtils.dropProcedureIfExists("ProcName", stmt); - } catch (Exception ex) { - fail(ex.toString()); - } + TestUtils.dropProcedureIfExists("ProcName", stmt); + } catch (Exception ex) { + fail(ex.toString()); } } - } 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 5f2b89fe2..ef33ddd9f 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 @@ -120,8 +120,8 @@ public void testBatchedUnprepare() throws SQLException { // Skipped for now due to unexpected failures. Not functional so not critical. /* * // Verify total cache use. int expectedCacheHits = iterations * 4; int allowedDiscrepency = 20; // Allow - * some discrepency in number of cache hits to not fail test ( // TODO: Follow up on why there is sometimes - * a discrepency in number of cache hits (less than expected). assertTrue(expectedCacheHits >= + * some discrepancy in number of cache hits to not fail test ( // TODO: Follow up on why there is sometimes + * a discrepancy in number of cache hits (less than expected). assertTrue(expectedCacheHits >= * executeSQLReturnFirstInt(con, verifyTotalCacheUsesQuery)); assertTrue(expectedCacheHits - * allowedDiscrepency < executeSQLReturnFirstInt(con, verifyTotalCacheUsesQuery)); */ diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java index 86f1fe7b3..774efbe12 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java @@ -41,88 +41,77 @@ public class WrapperTest extends AbstractTest { @Test public void wrapTest() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); - - try { - // First make sure that a statement can be unwrapped - boolean isWrapper = ((SQLServerStatement) stmt) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); - - MessageFormat form = new MessageFormat(TestResource.getResource("R_shouldBeWrapper")); - MessageFormat form2 = new MessageFormat(TestResource.getResource("R_shouldNotBeWrapper")); - Object[][] msgArgs = {{"SQLStatement", "self"}, {"SQLServerStatement", "ISQLServerStatement"}, - {"SQLServerCallableStatement", "SQLServerStatement"}, - {"SQLServerCallableStatement", "SQLServerStatement"}}; - - assertEquals(isWrapper, true, form.format(msgArgs[0])); - - isWrapper = ((SQLServerStatement) stmt) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[1])); - - isWrapper = ((SQLServerStatement) stmt) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerConnection")); - assertEquals(isWrapper, false, form2.format(msgArgs[1])); - - // Now make sure that we can unwrap a SQLServerCallableStatement to a SQLServerStatement - CallableStatement cs = con.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }"); - // Test the class first - isWrapper = ((SQLServerCallableStatement) cs) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[2])); - // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and make sure it - // succeeds. - SQLServerStatement stmt2 = (SQLServerStatement) ((SQLServerCallableStatement) cs) - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); - stmt2.setResponseBuffering("adaptive"); - // now test the interface - isWrapper = ((SQLServerCallableStatement) cs) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerCallableStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[1])); - - // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and make sure it - // succeeds. - ISQLServerPreparedStatement stmt4 = (ISQLServerPreparedStatement) ((SQLServerCallableStatement) cs) - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerPreparedStatement")); - stmt4.setResponseBuffering("adaptive"); - - if (isKatmaiServer()) - stmt4.setDateTimeOffset(1, null); - - // Try Unwrapping CallableStatement to a callableStatement - isWrapper = ((SQLServerCallableStatement) cs) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[3])); - // Now unwrap the Callable to a SQLServerCallableStatement and call a SQLServerStatement specific function - // and make sure it succeeds. - SQLServerCallableStatement stmt3 = (SQLServerCallableStatement) ((SQLServerCallableStatement) cs) - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement")); - stmt3.setResponseBuffering("adaptive"); - if (isKatmaiServer()) { - stmt3.setDateTimeOffset(1, null); - } - if (null != stmt4) { - stmt4.close(); - } - if (null != cs) { - cs.close(); - } - - } catch (UnsupportedOperationException e) { - assertEquals(System.getProperty("java.specification.version"), "1.5", - "isWrapperFor " + TestResource.getResource("R_shouldBeSupported")); - assertTrue(e.getMessage().equalsIgnoreCase("This operation is not supported."), - TestResource.getResource("R_unexpectedExceptionContent")); - } finally { - if (null != stmt) { - stmt.close(); - } - if (null != con) { - con.close(); + MessageFormat form = new MessageFormat(TestResource.getResource("R_shouldBeWrapper")); + MessageFormat form2 = new MessageFormat(TestResource.getResource("R_shouldNotBeWrapper")); + Object[][] msgArgs = {{"SQLStatement", "self"}, {"SQLServerStatement", "ISQLServerStatement"}, + {"SQLServerCallableStatement", "SQLServerStatement"}, + {"SQLServerCallableStatement", "SQLServerStatement"}}; + + try (Connection con = DriverManager.getConnection(connectionString)) { + try (Statement stmt = con.createStatement()) { + + // First make sure that a statement can be unwrapped + boolean isWrapper = ((SQLServerStatement) stmt) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); + + assertEquals(isWrapper, true, form.format(msgArgs[0])); + + isWrapper = ((SQLServerStatement) stmt) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[1])); + + isWrapper = ((SQLServerStatement) stmt) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerConnection")); + assertEquals(isWrapper, false, form2.format(msgArgs[1])); + + // Now make sure that we can unwrap a SQLServerCallableStatement to a SQLServerStatement + try (CallableStatement cs = con.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }")) { + // Test the class first + isWrapper = ((SQLServerCallableStatement) cs) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[2])); + // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and make sure it succeeds. + try (SQLServerStatement stmt2 = (SQLServerStatement) ((SQLServerCallableStatement) cs) + .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement"))) { + stmt2.setResponseBuffering("adaptive"); + + // now test the interface + isWrapper = ((SQLServerCallableStatement) cs).isWrapperFor( + Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerCallableStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[1])); + + // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and + // make sure it succeeds. + try (ISQLServerPreparedStatement stmt3 = (ISQLServerPreparedStatement) ((SQLServerCallableStatement) cs) + .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerPreparedStatement"))) { + stmt3.setResponseBuffering("adaptive"); + + if (isKatmaiServer()) + stmt3.setDateTimeOffset(1, null); + + // Try Unwrapping CallableStatement to a callableStatement + isWrapper = ((SQLServerCallableStatement) cs).isWrapperFor( + Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[3])); + // Now unwrap the Callable to a SQLServerCallableStatement and call a SQLServerStatement + // specific function and make sure it succeeds. + try (SQLServerCallableStatement stmt4 = (SQLServerCallableStatement) ((SQLServerCallableStatement) cs) + .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement"))) { + stmt4.setResponseBuffering("adaptive"); + if (isKatmaiServer()) { + stmt4.setDateTimeOffset(1, null); + } + } + } + } + } + } catch (UnsupportedOperationException e) { + assertEquals(System.getProperty("java.specification.version"), "1.5", + "isWrapperFor " + TestResource.getResource("R_shouldBeSupported")); + assertTrue(e.getMessage().equalsIgnoreCase("This operation is not supported."), + TestResource.getResource("R_unexpectedExceptionContent")); } } - } /** From 6b10eecb8c0ae3529f0e33c1ddae70df23bb802d Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Mon, 17 Sep 2018 10:28:55 -0700 Subject: [PATCH 12/15] more --- .../jdbc/AlwaysEncrypted/AESetup.java | 9 +- .../AlwaysEncrypted/PrecisionScaleTest.java | 1 - .../bulkCopy/BulkCopyColumnMappingTest.java | 184 +++++----- .../jdbc/bulkCopy/BulkCopyTestUtil.java | 10 +- .../microsoft/sqlserver/jdbc/bvt/bvtTest.java | 72 ++-- .../jdbc/connection/ConnectionDriverTest.java | 17 +- .../SQLServerSpatialDatatypeTest.java | 14 +- .../preparedStatement/RegressionTest.java | 266 +++++++------- .../sqlserver/jdbc/tvp/TVPAllTypes.java | 19 +- .../jdbc/tvp/TVPResultSetCursorTest.java | 2 +- .../statement/BatchExecuteWithErrorsTest.java | 341 +++++++++--------- .../jdbc/unit/statement/BatchTriggerTest.java | 6 +- .../jdbc/unit/statement/LimitEscapeTest.java | 99 ++--- 13 files changed, 530 insertions(+), 510 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 f3c63208b..070f4f321 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -106,10 +106,11 @@ public static void setUpConnection() throws TestAbortedException, Exception { info.setProperty("keyStoreLocation", keyPath); info.setProperty("keyStoreSecret", secretstrJks); - con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString, info); - stmt = (SQLServerStatement) con.createStatement(); - createCMK(keyStoreName, javaKeyAliases); - createCEK(storeProvider); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString, info); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + createCMK(keyStoreName, javaKeyAliases); + createCEK(storeProvider); + } } /** 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 431b0fce5..3d1e0d354 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -32,7 +32,6 @@ */ @RunWith(JUnitPlatform.class) public class PrecisionScaleTest extends AESetup { - private static SQLServerPreparedStatement pstmt = null; private static java.util.Date date = null; private static int offsetFromGMT = 0; 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 268867494..6ec94f091 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -56,18 +56,22 @@ public static void closeConnection() throws SQLException { @Test @DisplayName("BulkCopy:test no explicit column mapping") public void testNoExplicitCM() { + DBTable destTable = null; + try { + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); - // create dest table - DBTable destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy without explicit column mapping - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable); - - // drop dest table - stmt.dropTable(destTable); + // set up bulkCopy without explicit column mapping + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable); + } finally { + if (null != destTable) { + // drop dest table + stmt.dropTable(destTable); + } + } } @Test @@ -271,85 +275,85 @@ public void testImplicitMismatchCM() { public void testInvalidCM() { DBTable destTable = null; try { - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with wrong column names - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping("wrongFirst", "wrongSecond"); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with invalid ordinal, column no 65 does not exist - bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping(sourceTable.getColumnName(1), 65); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with invalid ordinal, column no 42 does not exist - bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping(42, destTable.getColumnName(1)); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with invalid ordinal, column no 42 and 65 do not exist - bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping(42, 65); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy while passing empty string as column mapping - bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping(sourceTable.getColumnName(1), " "); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with 0 ordinal column mapping - bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping(0, 0); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with negative ordinal column mapping - bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping(-3, -6); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); - - // create dest table - destTable = sourceTable.cloneSchema(); - stmt.createTable(destTable); - - // set up bulkCopy with Integer.MIN_VALUE and Integer.MAX_VALUE column mapping - bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - bulkWrapper.setColumnMapping(Integer.MIN_VALUE, Integer.MAX_VALUE); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with wrong column names + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping("wrongFirst", "wrongSecond"); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with invalid ordinal, column no 65 does not exist + bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping(sourceTable.getColumnName(1), 65); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with invalid ordinal, column no 42 does not exist + bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping(42, destTable.getColumnName(1)); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with invalid ordinal, column no 42 and 65 do not exist + bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping(42, 65); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy while passing empty string as column mapping + bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping(sourceTable.getColumnName(1), " "); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with 0 ordinal column mapping + bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping(0, 0); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with negative ordinal column mapping + bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping(-3, -6); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); + + // create dest table + destTable = sourceTable.cloneSchema(); + stmt.createTable(destTable); + + // set up bulkCopy with Integer.MIN_VALUE and Integer.MAX_VALUE column mapping + bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + bulkWrapper.setColumnMapping(Integer.MIN_VALUE, Integer.MAX_VALUE); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); } finally { if (null != destTable) { stmt.dropTable(destTable); 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 377601093..73e77c885 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java @@ -91,7 +91,9 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, bo } catch (SQLException ex) { fail(ex.getMessage()); } finally { - stmt.dropTable(destinationTable); + if (null != destinationTable) { + stmt.dropTable(destinationTable); + } } } catch (SQLException ex) { fail(ex.getMessage()); @@ -188,7 +190,9 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, DB fail(ex.getMessage()); } } finally { - stmt.dropTable(destinationTable); + if (null != destinationTable) { + stmt.dropTable(destinationTable); + } } } catch (SQLException e) { if (!fail) { @@ -246,7 +250,7 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, DB fail(ex.getMessage()); } } finally { - if (dropDest) { + if (dropDest && null != destinationTable) { stmt.dropTable(destinationTable); } } 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 d34a566fd..e74c225fa 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java @@ -280,9 +280,9 @@ public void testCreatepreparedStatement() throws SQLException { DBPreparedStatement pstmt = conn.prepareStatement(query)) { pstmt.setObject(1, new BigDecimal(value)); - DBResultSet rs = pstmt.executeQuery(); - rs.verify(table1); - rs.close(); + try (DBResultSet rs = pstmt.executeQuery()) { + rs.verify(table1); + } } } @@ -329,21 +329,21 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { try (DBConnection conn = new DBConnection(connectionString); DBStatement stmt1 = conn.createStatement(); DBStatement stmt2 = conn.createStatement()) { - DBResultSet rs1 = stmt1.selectAll(table1); - DBResultSet rs2 = stmt2.selectAll(table2); - - // Interleave resultset calls - rs1.next(); - rs1.verifyCurrentRow(table1); - rs2.next(); - rs2.verifyCurrentRow(table2); - rs1.next(); - rs1.verifyCurrentRow(table1); - rs1.verify(table1); - rs1.close(); - rs2.next(); - rs2.verify(table2); - rs2.close(); + try (DBResultSet rs1 = stmt1.selectAll(table1); DBResultSet rs2 = stmt2.selectAll(table2)) { + + // Interleave resultset calls + rs1.next(); + rs1.verifyCurrentRow(table1); + rs2.next(); + rs2.verifyCurrentRow(table2); + rs1.next(); + rs1.verifyCurrentRow(table1); + rs1.verify(table1); + rs1.close(); + rs2.next(); + rs2.verify(table2); + rs2.close(); + } } } @@ -356,25 +356,25 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { public void testTwoResultsetsSameStmt() throws SQLException { try (DBConnection conn = new DBConnection(connectionString); DBStatement stmt = conn.createStatement()) { - DBResultSet rs1 = stmt.selectAll(table1); - DBResultSet rs2 = stmt.selectAll(table2); - // Interleave resultset calls. rs is expected to be closed - try { - rs1.next(); - } catch (SQLException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_resultsetClosed")); - } - rs2.next(); - rs2.verifyCurrentRow(table2); - try { - rs1.next(); - } catch (SQLException e) { - assertEquals(e.getMessage(), TestResource.getResource("R_resultsetClosed")); + try (DBResultSet rs1 = stmt.selectAll(table1); DBResultSet rs2 = stmt.selectAll(table2)) { + // Interleave resultset calls. rs is expected to be closed + try { + rs1.next(); + } catch (SQLException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_resultsetClosed")); + } + rs2.next(); + rs2.verifyCurrentRow(table2); + try { + rs1.next(); + } catch (SQLException e) { + assertEquals(e.getMessage(), TestResource.getResource("R_resultsetClosed")); + } + rs1.close(); + rs2.next(); + rs2.verify(table2); + rs2.close(); } - rs1.close(); - rs2.next(); - rs2.verify(table2); - rs2.close(); } } 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 9881ab9c3..24b12f18e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -281,9 +281,10 @@ public void testNewConnection() throws SQLException { @Test public void testClosedConnection() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - conn.close(); - assertTrue(!conn.isValid(0), TestResource.getResource("R_closedConnectionShouldBeInvalid")); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + conn.close(); + assertTrue(!conn.isValid(0), TestResource.getResource("R_closedConnectionShouldBeInvalid")); + } } @Test @@ -331,10 +332,12 @@ public void testDeadConnection() throws SQLException { } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } finally { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";responseBuffering=adaptive"); - Statement stmt = conn.createStatement()) { - stmt.execute("drop table " + tableName); + if (null != tableName) { + try (SQLServerConnection conn = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";responseBuffering=adaptive"); + Statement stmt = conn.createStatement()) { + stmt.execute("drop table " + tableName); + } } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java index 5672a26c5..30fb14875 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java @@ -920,9 +920,10 @@ public void testCheckGeomMetaData() throws SQLException { String sqlTypeName = paramMetaData.getParameterTypeName(1); assertEquals(sqlType, -157); assertEquals(sqlTypeName, "geometry"); - SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geomTableName); - ResultSetMetaData rsmd = rs.getMetaData(); - assertEquals(rsmd.getColumnType(1), -157); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geomTableName)) { + ResultSetMetaData rsmd = rs.getMetaData(); + assertEquals(rsmd.getColumnType(1), -157); + } } } @@ -943,9 +944,10 @@ public void testCheckGeogMetaData() throws SQLException { String sqlTypeName = paramMetaData.getParameterTypeName(1); assertEquals(sqlType, -158); assertEquals(sqlTypeName, "geography"); - SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geogTableName); - ResultSetMetaData rsmd = rs.getMetaData(); - assertEquals(rsmd.getColumnType(1), -158); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geogTableName)) { + ResultSetMetaData rsmd = rs.getMetaData(); + assertEquals(rsmd.getColumnType(1), -158); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java index 8eae8958a..3ba34122b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java @@ -162,7 +162,98 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { modifyConnectionForBulkCopyAPI((SQLServerConnection) con); } - Statement stmt = con.createStatement(); + try (Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists("TEST_TABLE", stmt); + + con.setAutoCommit(false); + + // create a table with two columns + boolean createPrimaryKey = false; + try { + stmt.execute("if object_id('TEST_TABLE', 'U') is not null\ndrop table TEST_TABLE;"); + if (createPrimaryKey) { + stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max), primary key (ID) );"); + } else { + stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max) );"); + } + } catch (Exception e) { + fail(e.toString()); + } + + con.commit(); + + // build a String with 4001 characters + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < 4001; i++) { + stringBuilder.append('c'); + } + String largeString = stringBuilder.toString(); + + String[] values = {"a", "b", largeString, "d", "e"}; + // insert five rows into the table; use a batch for each row + try (PreparedStatement pstmt = con.prepareStatement("insert into TEST_TABLE values (?,?)")) { + // 0,a + pstmt.setInt(1, 0); + pstmt.setNString(2, values[0]); + pstmt.addBatch(); + + // 1,b + pstmt.setInt(1, 1); + pstmt.setNString(2, values[1]); + pstmt.addBatch(); + + // 2,ccc... + pstmt.setInt(1, 2); + pstmt.setNString(2, values[2]); + pstmt.addBatch(); + + // 3,d + pstmt.setInt(1, 3); + pstmt.setNString(2, values[3]); + pstmt.addBatch(); + + // 4,e + pstmt.setInt(1, 4); + pstmt.setNString(2, values[4]); + pstmt.addBatch(); + + pstmt.executeBatch(); + } catch (Exception e) { + fail(e.toString()); + } + con.commit(); + + // check the data in the table + Map selectedValues = new LinkedHashMap<>(); + int id = 0; + try (PreparedStatement pstmt = con.prepareStatement("select * from TEST_TABLE;")) { + try (ResultSet rs = pstmt.executeQuery()) { + int i = 0; + while (rs.next()) { + id = rs.getInt(1); + String data = rs.getNString(2); + if (selectedValues.containsKey(id)) { + fail("Found duplicate id: " + id + " ,actual values is : " + values[i++] + " data is: " + + data); + } + selectedValues.put(id, data); + } + } + } finally { + TestUtils.dropTableIfExists("TEST_TABLE", stmt); + } + } + } + } + + /** + * Test with large string and tests with more batch queries + * + * @throws SQLException + */ + @Test + public void addBatchWithLargeStringTest() throws SQLException { + try (Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists("TEST_TABLE", stmt); con.setAutoCommit(false); @@ -170,172 +261,75 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { // create a table with two columns boolean createPrimaryKey = false; try { - stmt.execute("if object_id('TEST_TABLE', 'U') is not null\ndrop table TEST_TABLE;"); + stmt.execute("if object_id('testTable', 'U') is not null\ndrop table testTable;"); if (createPrimaryKey) { - stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max), primary key (ID) );"); + stmt.execute("create table testTable ( ID int, DATA nvarchar(max), primary key (ID) );"); } else { - stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max) );"); + stmt.execute("create table testTable ( ID int, DATA nvarchar(max) );"); } } catch (Exception e) { fail(e.toString()); } - con.commit(); // build a String with 4001 characters StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 4001; i++) { - stringBuilder.append('c'); + stringBuilder.append('x'); } String largeString = stringBuilder.toString(); - String[] values = {"a", "b", largeString, "d", "e"}; // insert five rows into the table; use a batch for each row - try (PreparedStatement pstmt = con.prepareStatement("insert into TEST_TABLE values (?,?)")) { + try (PreparedStatement pstmt = con.prepareStatement("insert into testTable values (?,?), (?,?);")) { // 0,a + // 1,b pstmt.setInt(1, 0); - pstmt.setNString(2, values[0]); + pstmt.setNString(2, "a"); + pstmt.setInt(3, 1); + pstmt.setNString(4, "b"); pstmt.addBatch(); - // 1,b - pstmt.setInt(1, 1); - pstmt.setNString(2, values[1]); + // 2,c + // 3,d + pstmt.setInt(1, 2); + pstmt.setNString(2, "c"); + pstmt.setInt(3, 3); + pstmt.setNString(4, "d"); pstmt.addBatch(); - // 2,ccc... - pstmt.setInt(1, 2); - pstmt.setNString(2, values[2]); + // 4,xxx... + // 5,f + pstmt.setInt(1, 4); + pstmt.setNString(2, largeString); + pstmt.setInt(3, 5); + pstmt.setNString(4, "f"); pstmt.addBatch(); - // 3,d - pstmt.setInt(1, 3); - pstmt.setNString(2, values[3]); + // 6,g + // 7,h + pstmt.setInt(1, 6); + pstmt.setNString(2, "g"); + pstmt.setInt(3, 7); + pstmt.setNString(4, "h"); pstmt.addBatch(); - // 4,e - pstmt.setInt(1, 4); - pstmt.setNString(2, values[4]); + // 8,i + // 9,xxx... + pstmt.setInt(1, 8); + pstmt.setNString(2, "i"); + pstmt.setInt(3, 9); + pstmt.setNString(4, largeString); pstmt.addBatch(); pstmt.executeBatch(); - } catch (Exception e) { - fail(e.toString()); - } - con.commit(); - // check the data in the table - Map selectedValues = new LinkedHashMap<>(); - int id = 0; - try (PreparedStatement pstmt = con.prepareStatement("select * from TEST_TABLE;")) { - try (ResultSet rs = pstmt.executeQuery()) { - int i = 0; - while (rs.next()) { - id = rs.getInt(1); - String data = rs.getNString(2); - if (selectedValues.containsKey(id)) { - fail("Found duplicate id: " + id + " ,actual values is : " + values[i++] + " data is: " - + data); - } - selectedValues.put(id, data); - } - } - } finally { - TestUtils.dropTableIfExists("TEST_TABLE", stmt); - if (null != stmt) { - stmt.close(); - } + con.commit(); } - } - } - /** - * Test with large string and tests with more batch queries - * - * @throws SQLException - */ - @Test - public void addBatchWithLargeStringTest() throws SQLException { - Statement stmt = con.createStatement(); - PreparedStatement pstmt = null; - TestUtils.dropTableIfExists("TEST_TABLE", stmt); - - con.setAutoCommit(false); - - // create a table with two columns - boolean createPrimaryKey = false; - try { - stmt.execute("if object_id('testTable', 'U') is not null\ndrop table testTable;"); - if (createPrimaryKey) { - stmt.execute("create table testTable ( ID int, DATA nvarchar(max), primary key (ID) );"); - } else { - stmt.execute("create table testTable ( ID int, DATA nvarchar(max) );"); - } - } catch (Exception e) { - fail(e.toString()); - } - con.commit(); - - // build a String with 4001 characters - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < 4001; i++) { - stringBuilder.append('x'); - } - String largeString = stringBuilder.toString(); - - // insert five rows into the table; use a batch for each row - try { - pstmt = con.prepareStatement("insert into testTable values (?,?), (?,?);"); - // 0,a - // 1,b - pstmt.setInt(1, 0); - pstmt.setNString(2, "a"); - pstmt.setInt(3, 1); - pstmt.setNString(4, "b"); - pstmt.addBatch(); - - // 2,c - // 3,d - pstmt.setInt(1, 2); - pstmt.setNString(2, "c"); - pstmt.setInt(3, 3); - pstmt.setNString(4, "d"); - pstmt.addBatch(); - - // 4,xxx... - // 5,f - pstmt.setInt(1, 4); - pstmt.setNString(2, largeString); - pstmt.setInt(3, 5); - pstmt.setNString(4, "f"); - pstmt.addBatch(); - - // 6,g - // 7,h - pstmt.setInt(1, 6); - pstmt.setNString(2, "g"); - pstmt.setInt(3, 7); - pstmt.setNString(4, "h"); - pstmt.addBatch(); - - // 8,i - // 9,xxx... - pstmt.setInt(1, 8); - pstmt.setNString(2, "i"); - pstmt.setInt(3, 9); - pstmt.setNString(4, largeString); - pstmt.addBatch(); - - pstmt.executeBatch(); - - con.commit(); - } - - catch (Exception e) { - fail(e.toString()); - } finally { - TestUtils.dropTableIfExists("testTable", stmt); - if (null != stmt) { - stmt.close(); + catch (Exception e) { + fail(e.toString()); + } finally { + TestUtils.dropTableIfExists("testTable", stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java index cc676cdbb..712a2e46e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java @@ -172,19 +172,20 @@ private void setupVariation(boolean setSelectMethod, Integer resultSetType, Inte TestUtils.dropProcedureIfExists(procedureName, stmt); dropTVPS(tvpName); - DBConnection dbConnection = new DBConnection(connectionString); - DBStatement dbStmt = dbConnection.createStatement(); + try (DBConnection dbConnection = new DBConnection(connectionString); + DBStatement dbStmt = dbConnection.createStatement()) { - tableSrc = new DBTable(true); - tableDest = tableSrc.cloneSchema(); + tableSrc = new DBTable(true); + tableDest = tableSrc.cloneSchema(); - dbStmt.createTable(tableSrc); - dbStmt.createTable(tableDest); + dbStmt.createTable(tableSrc); + dbStmt.createTable(tableDest); - createTVPS(tvpName, tableSrc.getDefinitionOfColumns()); - createPreocedure(procedureName, tableDest.getEscapedTableName()); + createTVPS(tvpName, tableSrc.getDefinitionOfColumns()); + createPreocedure(procedureName, tableDest.getEscapedTableName()); - dbStmt.populateTable(tableSrc); + dbStmt.populateTable(tableSrc); + } } private void terminateVariation() throws SQLException { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java index fb74cde68..0c522fdbd 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java @@ -381,7 +381,7 @@ private static void createPreocedure() throws SQLException { String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + desTable + " SELECT * FROM @InputData" + " END"; - stmt.execute(sql); + stmt.execute(sql); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java index e422bfbc1..519488446 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java @@ -310,152 +310,16 @@ private void Repro47239largeInternal(String mode) throws Exception { assumeTrue("JDBC42".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); // the DBConnection for detecting whether the server is SQL Azure or SQL Server. - con = DriverManager.getConnection(connectionString); - final String warning; - final String error; - final String severe; - if (DBConnection.isSqlAzure(con)) { - // SQL Azure will throw exception for "raiserror WITH LOG", so the following RAISERROR statements have not - // "with log" option - warning = "RAISERROR ('raiserror level 4',4,1)"; - error = "RAISERROR ('raiserror level 11',11,1)"; - // On SQL Azure, raising FATAL error by RAISERROR() is not supported and there is no way to - // cut the current connection by a statement inside a SQL batch. - // Details: Although one can simulate a fatal error (that cuts the connections) by dropping the database, - // this simulation cannot be written entirely in TSQL (because it needs a new connection), - // and thus it cannot be put into a TSQL batch and it is useless here. - // So we have to skip the last scenario of this test case, i.e. "Test Severe (connection-closing) errors" - // It is worthwhile to still execute the first 5 test scenarios of this test case, in order to have best - // test coverage. - severe = "--Not executed when testing against SQL Azure"; // this is a dummy statement that never being - // executed on SQL Azure - } else { - warning = "RAISERROR ('raiserror level 4',4,1) WITH LOG"; - error = "RAISERROR ('raiserror level 11',11,1) WITH LOG"; - severe = "RAISERROR ('raiserror level 20',20,1) WITH LOG"; - } - con.close(); - - long[] actualUpdateCounts; - long[] expectedUpdateCounts; - String actualExceptionText; - - // SQL Server 2005 driver - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - - try (Connection conn = DriverManager.getConnection(connectionString)) { - if (mode.equalsIgnoreCase("bulkcopy")) { - modifyConnectionForBulkCopyAPI((SQLServerConnection) conn); - } - try (Statement stmt = conn.createStatement()) { - - try { - TestUtils.dropTableIfExists(tableName, stmt); - } catch (Exception ignored) {} - try { - stmt.executeLargeUpdate("create table " + tableName - + " (c1_int int, c2_varchar varchar(20), c3_date datetime, c4_int int identity(1,1) primary key)"); - } catch (Exception ignored) {} - // Regular Statement batch update - expectedUpdateCounts = new long[] {1, -2, 1, -2, 1, -2}; - try (Statement batchStmt = conn.createStatement()) { - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - batchStmt.addBatch(insertStmt); - batchStmt.addBatch(warning); - try { - actualUpdateCounts = batchStmt.executeLargeBatch(); - actualExceptionText = ""; - } catch (BatchUpdateException bue) { - actualUpdateCounts = bue.getLargeUpdateCounts(); - actualExceptionText = bue.getMessage(); - log.fine("BatchUpdateException occurred. Message:" + actualExceptionText); - } - } - - log.fine("UpdateCounts:"); - for (long updateCount : actualUpdateCounts) { - log.fine("" + updateCount + ","); - } - log.fine(""); - assertTrue(Arrays.equals(actualUpdateCounts, expectedUpdateCounts), - TestResource.getResource("R_testInterleaved")); - - expectedUpdateCounts = new long[] {-3, 1, 1, 1}; - stmt.addBatch(error); - stmt.addBatch(insertStmt); - stmt.addBatch(insertStmt); - stmt.addBatch(insertStmt); - try { - actualUpdateCounts = stmt.executeLargeBatch(); - actualExceptionText = ""; - } catch (BatchUpdateException bue) { - actualUpdateCounts = bue.getLargeUpdateCounts(); - actualExceptionText = bue.getMessage(); - } - log.fine("UpdateCounts:"); - for (long updateCount : actualUpdateCounts) { - log.fine("" + updateCount + ","); - } - log.fine(""); - assertTrue(Arrays.equals(actualUpdateCounts, expectedUpdateCounts), - TestResource.getResource("R_errorFollowInserts")); - - // 50280 - expectedUpdateCounts = new long[] {1, -3}; - stmt.addBatch(insertStmt); - stmt.addBatch(error16); - try { - actualUpdateCounts = stmt.executeLargeBatch(); - actualExceptionText = ""; - } catch (BatchUpdateException bue) { - actualUpdateCounts = bue.getLargeUpdateCounts(); - actualExceptionText = bue.getMessage(); - } - for (long updateCount : actualUpdateCounts) { - log.fine("" + updateCount + ","); - } - log.fine(""); - assertTrue(Arrays.equals(actualUpdateCounts, expectedUpdateCounts), - TestResource.getResource("R_errorFollow50280")); - - // Test "soft" errors - conn.setAutoCommit(false); - stmt.addBatch(select); - stmt.addBatch(insertStmt); - stmt.addBatch(select); - stmt.addBatch(insertStmt); - try { - stmt.executeLargeBatch(); - // Soft error test: executeLargeBatch unexpectedly succeeded - assertEquals(false, true, TestResource.getResource("R_shouldThrowException")); - } catch (BatchUpdateException bue) { - // Soft error test: wrong error message in BatchUpdateException - assertEquals("A result set was generated for update.", bue.getMessage(), - TestResource.getResource("R_unexpectedExceptionContent")); - // Soft error test: wrong update counts in BatchUpdateException - assertEquals(Arrays.equals(bue.getLargeUpdateCounts(), new long[] {-3, 1, -3, 1}), true, - TestResource.getResource("R_incorrectUpdateCount")); - } - conn.rollback(); - - // Defect 128801: Rollback (with conversion error) should throw SQLException - stmt.addBatch(dateConversionError); - stmt.addBatch(insertStmt); - stmt.addBatch(insertStmt); - stmt.addBatch(insertStmt); - try { - stmt.executeLargeBatch(); - } catch (BatchUpdateException bue) { - assertThat(bue.getMessage(), containsString(TestResource.getResource("R_syntaxErrorDateConvert"))); - } catch (SQLException e) { - assertThat(e.getMessage(), containsString(TestResource.getResource("R_dateConvertError"))); - } - - conn.setAutoCommit(true); - + try (Connection con = DriverManager.getConnection(connectionString)) { + final String warning; + final String error; + final String severe; + if (DBConnection.isSqlAzure(con)) { + // SQL Azure will throw exception for "raiserror WITH LOG", so the following RAISERROR statements have + // not + // "with log" option + warning = "RAISERROR ('raiserror level 4',4,1)"; + error = "RAISERROR ('raiserror level 11',11,1)"; // On SQL Azure, raising FATAL error by RAISERROR() is not supported and there is no way to // cut the current connection by a statement inside a SQL batch. // Details: Although one can simulate a fatal error (that cuts the connections) by dropping the @@ -466,42 +330,185 @@ private void Repro47239largeInternal(String mode) throws Exception { // errors" // It is worthwhile to still execute the first 5 test scenarios of this test case, in order to have best // test coverage. - if (!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString))) { - // Test Severe (connection-closing) errors + severe = "--Not executed when testing against SQL Azure"; // this is a dummy statement that never being + // executed on SQL Azure + } else { + warning = "RAISERROR ('raiserror level 4',4,1) WITH LOG"; + error = "RAISERROR ('raiserror level 11',11,1) WITH LOG"; + severe = "RAISERROR ('raiserror level 20',20,1) WITH LOG"; + } + con.close(); + + long[] actualUpdateCounts; + long[] expectedUpdateCounts; + String actualExceptionText; + + // SQL Server 2005 driver + Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); + + try (Connection conn = DriverManager.getConnection(connectionString)) { + if (mode.equalsIgnoreCase("bulkcopy")) { + modifyConnectionForBulkCopyAPI((SQLServerConnection) conn); + } + try (Statement stmt = conn.createStatement()) { + + try { + TestUtils.dropTableIfExists(tableName, stmt); + } catch (Exception ignored) {} + try { + stmt.executeLargeUpdate("create table " + tableName + + " (c1_int int, c2_varchar varchar(20), c3_date datetime, c4_int int identity(1,1) primary key)"); + } catch (Exception ignored) {} + // Regular Statement batch update + expectedUpdateCounts = new long[] {1, -2, 1, -2, 1, -2}; + try (Statement batchStmt = conn.createStatement()) { + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + batchStmt.addBatch(insertStmt); + batchStmt.addBatch(warning); + try { + actualUpdateCounts = batchStmt.executeLargeBatch(); + actualExceptionText = ""; + } catch (BatchUpdateException bue) { + actualUpdateCounts = bue.getLargeUpdateCounts(); + actualExceptionText = bue.getMessage(); + log.fine("BatchUpdateException occurred. Message:" + actualExceptionText); + } + } + + log.fine("UpdateCounts:"); + for (long updateCount : actualUpdateCounts) { + log.fine("" + updateCount + ","); + } + log.fine(""); + assertTrue(Arrays.equals(actualUpdateCounts, expectedUpdateCounts), + TestResource.getResource("R_testInterleaved")); + + expectedUpdateCounts = new long[] {-3, 1, 1, 1}; stmt.addBatch(error); stmt.addBatch(insertStmt); - stmt.addBatch(warning); + stmt.addBatch(insertStmt); + stmt.addBatch(insertStmt); + try { + actualUpdateCounts = stmt.executeLargeBatch(); + actualExceptionText = ""; + } catch (BatchUpdateException bue) { + actualUpdateCounts = bue.getLargeUpdateCounts(); + actualExceptionText = bue.getMessage(); + } + log.fine("UpdateCounts:"); + for (long updateCount : actualUpdateCounts) { + log.fine("" + updateCount + ","); + } + log.fine(""); + assertTrue(Arrays.equals(actualUpdateCounts, expectedUpdateCounts), + TestResource.getResource("R_errorFollowInserts")); + // 50280 + expectedUpdateCounts = new long[] {1, -3}; stmt.addBatch(insertStmt); - stmt.addBatch(severe); + stmt.addBatch(error16); + try { + actualUpdateCounts = stmt.executeLargeBatch(); + actualExceptionText = ""; + } catch (BatchUpdateException bue) { + actualUpdateCounts = bue.getLargeUpdateCounts(); + actualExceptionText = bue.getMessage(); + } + for (long updateCount : actualUpdateCounts) { + log.fine("" + updateCount + ","); + } + log.fine(""); + assertTrue(Arrays.equals(actualUpdateCounts, expectedUpdateCounts), + TestResource.getResource("R_errorFollow50280")); + + // Test "soft" errors + conn.setAutoCommit(false); + stmt.addBatch(select); stmt.addBatch(insertStmt); + stmt.addBatch(select); stmt.addBatch(insertStmt); try { stmt.executeLargeBatch(); - // Test fatal errors batch execution succeeded (should have failed) + // Soft error test: executeLargeBatch unexpectedly succeeded assertEquals(false, true, TestResource.getResource("R_shouldThrowException")); } catch (BatchUpdateException bue) { - // Test fatal errors returned BatchUpdateException rather than SQLException - assertEquals(false, true, TestResource.getResource("R_unexpectedException") + bue.getMessage()); - } catch (SQLException e) { - actualExceptionText = e.getMessage(); + // Soft error test: wrong error message in BatchUpdateException + assertEquals("A result set was generated for update.", bue.getMessage(), + TestResource.getResource("R_unexpectedExceptionContent")); + // Soft error test: wrong update counts in BatchUpdateException + assertEquals(Arrays.equals(bue.getLargeUpdateCounts(), new long[] {-3, 1, -3, 1}), true, + TestResource.getResource("R_incorrectUpdateCount")); + } + conn.rollback(); - if (actualExceptionText.endsWith("reset")) { - assertTrue(actualExceptionText.equalsIgnoreCase("Connection reset"), - TestResource.getResource("R_unexpectedExceptionContent") + ": " - + actualExceptionText); - } else { - assertTrue(actualExceptionText.equalsIgnoreCase("raiserror level 20"), - TestResource.getResource("R_unexpectedExceptionContent") + ": " - + actualExceptionText); + // Defect 128801: Rollback (with conversion error) should throw SQLException + stmt.addBatch(dateConversionError); + stmt.addBatch(insertStmt); + stmt.addBatch(insertStmt); + stmt.addBatch(insertStmt); + try { + stmt.executeLargeBatch(); + } catch (BatchUpdateException bue) { + assertThat(bue.getMessage(), + containsString(TestResource.getResource("R_syntaxErrorDateConvert"))); + } catch (SQLException e) { + assertThat(e.getMessage(), containsString(TestResource.getResource("R_dateConvertError"))); + } + conn.setAutoCommit(true); + + // On SQL Azure, raising FATAL error by RAISERROR() is not supported and there is no way to + // cut the current connection by a statement inside a SQL batch. + // Details: Although one can simulate a fatal error (that cuts the connections) by dropping the + // database, + // this simulation cannot be written entirely in TSQL (because it needs a new connection), + // and thus it cannot be put into a TSQL batch and it is useless here. + // So we have to skip the last scenario of this test case, i.e. "Test Severe (connection-closing) + // errors" + // It is worthwhile to still execute the first 5 test scenarios of this test case, in order to have + // best + // test coverage. + if (!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString))) { + // Test Severe (connection-closing) errors + stmt.addBatch(error); + stmt.addBatch(insertStmt); + stmt.addBatch(warning); + + stmt.addBatch(insertStmt); + stmt.addBatch(severe); + stmt.addBatch(insertStmt); + stmt.addBatch(insertStmt); + try { + stmt.executeLargeBatch(); + // Test fatal errors batch execution succeeded (should have failed) + assertEquals(false, true, TestResource.getResource("R_shouldThrowException")); + } catch (BatchUpdateException bue) { + // Test fatal errors returned BatchUpdateException rather than SQLException + assertEquals(false, true, + TestResource.getResource("R_unexpectedException") + bue.getMessage()); + } catch (SQLException e) { + actualExceptionText = e.getMessage(); + + if (actualExceptionText.endsWith("reset")) { + assertTrue(actualExceptionText.equalsIgnoreCase("Connection reset"), + TestResource.getResource("R_unexpectedExceptionContent") + ": " + + actualExceptionText); + } else { + assertTrue(actualExceptionText.equalsIgnoreCase("raiserror level 20"), + TestResource.getResource("R_unexpectedExceptionContent") + ": " + + actualExceptionText); + + } } } - } - try { - stmt.executeLargeUpdate("drop table " + tableName); - } catch (Exception ignored) {} + try { + stmt.executeLargeUpdate("drop table " + tableName); + } catch (Exception ignored) {} + } } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java index b72cda221..406a7d5e7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java @@ -61,7 +61,8 @@ public void statementTest() throws SQLException { */ @Test public void preparedStatementTest() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); PreparedStatement pstmt = connection.prepareStatement(insertQuery)) { + try (Connection connection = DriverManager.getConnection(connectionString); + PreparedStatement pstmt = connection.prepareStatement(insertQuery)) { pstmt.addBatch(); pstmt.executeBatch(); @@ -126,7 +127,8 @@ public static void testSetup() throws TestAbortedException, Exception { * @throws SQLException */ private static void dropTable() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); } } 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 197e2787e..e94d42d2a 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 @@ -52,7 +52,9 @@ static class Query { boolean callable = false; int preparedCount = 0; boolean verifyResult = true; - ResultSet resultSet; + ResultSet resultSet = null; + PreparedStatement pstmt = null; + Statement stmt = null; int queryID; int queryId = 0; static int queryCount = 0; @@ -117,7 +119,7 @@ public void setverifyResult(boolean val) { } void executeSpecific(Connection conn) throws Exception { - Statement stmt = conn.createStatement(); + stmt = conn.createStatement(); resultSet = stmt.executeQuery(inputSql); } @@ -181,7 +183,7 @@ static class PreparedQuery extends Query { } void executeSpecific(Connection conn) throws Exception { - PreparedStatement pstmt = conn.prepareStatement(inputSql); + pstmt = conn.prepareStatement(inputSql); for (int i = 1; i <= placeholderCount; ++i) { pstmt.setObject(i, i); } @@ -196,53 +198,56 @@ static class CallableQuery extends PreparedQuery { } void execute(Connection conn) throws Exception { - CallableStatement cstmt = conn.prepareCall(inputSql); - for (int i = 1; i <= placeholderCount; ++i) { - cstmt.setObject(i, i); + try (CallableStatement cstmt = conn.prepareCall(inputSql)) { + for (int i = 1; i <= placeholderCount; ++i) { + cstmt.setObject(i, i); + } + resultSet = cstmt.executeQuery(); } - resultSet = cstmt.executeQuery(); } } public static void createAndPopulateTables(Connection conn) throws Exception { - Statement stmt = conn.createStatement(); - // Instead of table identifiers use some simple table names for this test only, as a lot of string manipulation - // is done - // around table names. - try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t1"); - } catch (Exception ex) {} ; - try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t2"); - } catch (Exception ex) {} ; - try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t3"); - } catch (Exception ex) {} ; - try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t4"); - } catch (Exception ex) {} ; - try { - stmt.executeUpdate("drop procedure UnitStatement_LimitEscape_p1"); - } catch (Exception ex) {} ; - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t1 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t2 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t3 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t4 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t1 values " + "(1, 1, 'col3', 'col4'), " - + "(2, 2, 'row2 '' with '' quote', 'row2 with limit {limit 22} {limit ?}')," - + "(3, 3, 'row3 with subquery (select * from t1)', 'row3 with subquery (select * from (select * from t1) {limit 4})')," - + "(4, 4, 'select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)')," - + "(5, 5, 'openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')')"); - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t2 values (11, 11, 'col33', 'col44')"); - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t3 values (111, 111, 'col333', 'col444')"); - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t4 values (1111, 1111, 'col4444', 'col4444')"); - String query = "create procedure UnitStatement_LimitEscape_p1 @col3Value varchar(512), @col4Value varchar(512) AS BEGIN SELECT TOP 1 * from UnitStatement_LimitEscape_t1 where col3 = @col3Value and col4 = @col4Value END"; - stmt.execute(query); + try (Statement stmt = conn.createStatement()) { + // Instead of table identifiers use some simple table names for this test only, as a lot of string + // manipulation + // is done + // around table names. + try { + stmt.executeUpdate("drop table UnitStatement_LimitEscape_t1"); + } catch (Exception ex) {} ; + try { + stmt.executeUpdate("drop table UnitStatement_LimitEscape_t2"); + } catch (Exception ex) {} ; + try { + stmt.executeUpdate("drop table UnitStatement_LimitEscape_t3"); + } catch (Exception ex) {} ; + try { + stmt.executeUpdate("drop table UnitStatement_LimitEscape_t4"); + } catch (Exception ex) {} ; + try { + stmt.executeUpdate("drop procedure UnitStatement_LimitEscape_p1"); + } catch (Exception ex) {} ; + stmt.executeUpdate( + "create table UnitStatement_LimitEscape_t1 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate( + "create table UnitStatement_LimitEscape_t2 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate( + "create table UnitStatement_LimitEscape_t3 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate( + "create table UnitStatement_LimitEscape_t4 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + + stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t1 values " + "(1, 1, 'col3', 'col4'), " + + "(2, 2, 'row2 '' with '' quote', 'row2 with limit {limit 22} {limit ?}')," + + "(3, 3, 'row3 with subquery (select * from t1)', 'row3 with subquery (select * from (select * from t1) {limit 4})')," + + "(4, 4, 'select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)')," + + "(5, 5, 'openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')')"); + stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t2 values (11, 11, 'col33', 'col44')"); + stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t3 values (111, 111, 'col333', 'col444')"); + stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t4 values (1111, 1111, 'col4444', 'col4444')"); + String query = "create procedure UnitStatement_LimitEscape_p1 @col3Value varchar(512), @col4Value varchar(512) AS BEGIN SELECT TOP 1 * from UnitStatement_LimitEscape_t1 where col3 = @col3Value and col4 = @col4Value END"; + stmt.execute(query); + } } /** @@ -777,8 +782,7 @@ public static void beforeAll() { @AfterAll public static void afterAll() throws Exception { - Statement stmt = conn.createStatement(); - try { + try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); @@ -786,7 +790,6 @@ public static void afterAll() throws Exception { } catch (Exception ex) { fail(ex.toString()); } finally { - stmt.close(); conn.close(); } From e1038baf186798fd7bedd87c379139dba177756f Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Mon, 17 Sep 2018 11:29:10 -0700 Subject: [PATCH 13/15] spacing change only --- src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java index 5cc92dfb8..661cd791f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java @@ -566,7 +566,6 @@ public static Object roundDatetimeValue(Object value) { case 1: ts.setNanos((millis - 1) * 1000000); break; - // 2, 3, 4 -> 3 case 2: ts.setNanos((millis + 1) * 1000000); @@ -574,7 +573,6 @@ public static Object roundDatetimeValue(Object value) { case 4: ts.setNanos((millis - 1) * 1000000); break; - // 5, 6, 7, 8 -> 7 case 5: ts.setNanos((millis + 2) * 1000000); @@ -585,13 +583,11 @@ public static Object roundDatetimeValue(Object value) { case 8: ts.setNanos((millis - 1) * 1000000); break; - // 9 -> 0 with overflow case 9: ts.setNanos(0); ts.setTime(ts.getTime() + millis + 1); break; - // default, i.e. 0, 3, 7 -> 0, 3, 7 // don't change the millis but make sure that any // sub-millisecond digits are zeroed out From fad3cdb628cbbbaf504decea3bd640f22412e2a5 Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Mon, 17 Sep 2018 17:39:16 -0700 Subject: [PATCH 14/15] use shared statement in Abstract test again, this will be removed in another PR --- .../jdbc/AlwaysEncrypted/AESetup.java | 82 +++++++++++-------- 1 file changed, 46 insertions(+), 36 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 070f4f321..3f330857b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -87,10 +87,10 @@ public static void setUpConnection() throws TestAbortedException, Exception { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - String AETestConenctionString = connectionString + ";sendTimeAsDateTime=false"; + String AETestConnectionString = connectionString + ";sendTimeAsDateTime=false"; readFromFile(javaKeyStoreInputFile, "Alias name"); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropCEK(stmt); dropCMK(stmt); @@ -106,11 +106,10 @@ public static void setUpConnection() throws TestAbortedException, Exception { info.setProperty("keyStoreLocation", keyPath); info.setProperty("keyStoreSecret", secretstrJks); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString, info); - SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { - createCMK(keyStoreName, javaKeyAliases); - createCEK(storeProvider); - } + con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, info); + stmt = (SQLServerStatement) con.createStatement(); + createCMK(keyStoreName, javaKeyAliases); + createCEK(storeProvider); } /** @@ -684,10 +683,14 @@ protected static LinkedList createTemporalTypes(boolean nullable) { * @throws SQLException */ private static void createCMK(String keyStoreName, String keyPath) throws SQLException { - String sql = " if not exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')" + " begin" - + " CREATE COLUMN MASTER KEY " + cmkName + " WITH (KEY_STORE_PROVIDER_NAME = '" + keyStoreName - + "', KEY_PATH = '" + keyPath + "')" + " end"; - stmt.execute(sql); + try (SQLServerConnection con = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String sql = " if not exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')" + + " begin" + " CREATE COLUMN MASTER KEY " + cmkName + " WITH (KEY_STORE_PROVIDER_NAME = '" + + keyStoreName + "', KEY_PATH = '" + keyPath + "')" + " end"; + stmt.execute(sql); + } } /** @@ -698,13 +701,18 @@ private static void createCMK(String keyStoreName, String keyPath) throws SQLExc * @throws SQLException */ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storeProvider) throws SQLException { - String letters = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - byte[] valuesDefault = letters.getBytes(); - 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" + TestUtils.bytesToHexString(key, key.length) + ")" + ";"; - stmt.execute(cekSql); + try (SQLServerConnection con = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String letters = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + byte[] valuesDefault = letters.getBytes(); + 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" + TestUtils.bytesToHexString(key, key.length) + + ")" + ";"; + stmt.execute(cekSql); + } } /** @@ -729,8 +737,10 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager + .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // binary20 for (int i = 1; i <= 3; i++) { @@ -792,7 +802,7 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // binary(20) for (int i = 1; i <= 3; i++) { @@ -1018,7 +1028,7 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // char for (int i = 1; i <= 3; i++) { @@ -1080,7 +1090,7 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // char for (int i = 1; i <= 3; i++) { @@ -1141,7 +1151,7 @@ protected static void populateCharNullCase() throws SQLException { + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // char for (int i = 1; i <= 3; i++) { @@ -1194,7 +1204,7 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // date for (int i = 1; i <= 3; i++) { @@ -1240,7 +1250,7 @@ protected static void populateDateScaleNormalCase(LinkedList dateValues) String sql = "insert into " + scaleDateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // datetime2(2) for (int i = 1; i <= 3; i++) { @@ -1277,7 +1287,7 @@ protected static void populateDateSetObject(LinkedList dateValues, Strin + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // date for (int i = 1; i <= 3; i++) { @@ -1343,7 +1353,7 @@ protected void populateDateSetObjectNull() throws SQLException { + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // date for (int i = 1; i <= 3; i++) { @@ -1389,7 +1399,7 @@ protected static void populateDateNullCase() throws SQLException { + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // date for (int i = 1; i <= 3; i++) { @@ -1437,7 +1447,7 @@ protected static void populateNumeric(String[] values) throws SQLException { + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -1545,7 +1555,7 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -1653,7 +1663,7 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -1760,7 +1770,7 @@ protected static void populateNumericSetObjectNull() throws SQLException { + "?,?,?," + "?,?,?" + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -1860,7 +1870,7 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -1959,7 +1969,7 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S + ")"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -2086,6 +2096,6 @@ private static void dropCMK(SQLServerStatement stmt) throws SQLException { * @throws TestAbortedException */ protected static void skipTestForJava7() throws TestAbortedException, SQLException { - assumeTrue(TestUtils.supportJDBC42(con)); // With Java 7, skip tests for JDBCType. + assumeTrue(TestUtils.supportJDBC42(con)); // With Java 7, skip tests for JDBCType. } } From b4060e6a366b740a02e43bd37fb5a5a0f570efba Mon Sep 17 00:00:00 2001 From: "v-susanh@microsoft.com" Date: Tue, 18 Sep 2018 12:43:30 -0700 Subject: [PATCH 15/15] try-with-resources for Stream types --- .../DatabaseMetaDataTest.java | 35 ++--- .../sqlserver/jdbc/unit/lobs/lobsTest.java | 139 ++++++++++-------- 2 files changed, 93 insertions(+), 81 deletions(-) diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index 739d99908..ed63ae14f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -84,30 +84,31 @@ public void testDriverVersion() throws SQLException, IOException { assumeTrue(f.exists(), TestResource.getResource("R_manifestNotFound")); - InputStream in = new BufferedInputStream(new FileInputStream(f)); - Manifest manifest = new Manifest(in); - Attributes attributes = manifest.getMainAttributes(); - String buildVersion = attributes.getValue("Bundle-Version"); + try (InputStream in = new BufferedInputStream(new FileInputStream(f))) { + Manifest manifest = new Manifest(in); + Attributes attributes = manifest.getMainAttributes(); + String buildVersion = attributes.getValue("Bundle-Version"); - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - DatabaseMetaData dbmData = conn.getMetaData(); + DatabaseMetaData dbmData = conn.getMetaData(); - String driverVersion = dbmData.getDriverVersion(); + String driverVersion = dbmData.getDriverVersion(); - boolean isSnapshot = buildVersion.contains("SNAPSHOT"); + boolean isSnapshot = buildVersion.contains("SNAPSHOT"); - // Removing all dots & chars easy for comparing. - driverVersion = driverVersion.replaceAll("[^0-9]", ""); - buildVersion = buildVersion.replaceAll("[^0-9]", ""); + // Removing all dots & chars easy for comparing. + driverVersion = driverVersion.replaceAll("[^0-9]", ""); + buildVersion = buildVersion.replaceAll("[^0-9]", ""); - // Not comparing last build number. We will compare only major.minor.patch - driverVersion = driverVersion.substring(0, 3); - buildVersion = buildVersion.substring(0, 3); + // Not comparing last build number. We will compare only major.minor.patch + driverVersion = driverVersion.substring(0, 3); + buildVersion = buildVersion.substring(0, 3); - int intBuildVersion = Integer.valueOf(buildVersion); - int intDriverVersion = Integer.valueOf(driverVersion); - assertTrue(intDriverVersion == intBuildVersion, TestResource.getResource("R_buildVersionError")); + int intBuildVersion = Integer.valueOf(buildVersion); + int intDriverVersion = Integer.valueOf(driverVersion); + assertTrue(intDriverVersion == intBuildVersion, TestResource.getResource("R_buildVersionError")); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java index b718ec046..9166638ae 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java @@ -248,7 +248,6 @@ private void testFreedBlobs(Class lobClass, boolean isResultSet) throws SQLExcep ThreadLocalRandom.current().nextBytes(data); Blob blob = null; - InputStream stream = null; for (int i = 0; i < 5; i++) { try (PreparedStatement ps = conn .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { @@ -265,27 +264,23 @@ private void testFreedBlobs(Class lobClass, boolean isResultSet) throws SQLExcep rs.next(); blob = rs.getBlob(2); - stream = blob.getBinaryStream(); - while (stream.available() > 0) - stream.read(); - blob.free(); - try { - stream = blob.getBinaryStream(); - } catch (SQLException e) { + try (InputStream stream = blob.getBinaryStream()) { + while (stream.available() > 0) + stream.read(); + blob.free(); + } + try (InputStream stream = blob.getBinaryStream()) {} catch (SQLException e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); } } } - try { - stream = blob.getBinaryStream(); - } catch (SQLException e) { + try (InputStream stream = blob.getBinaryStream()) {} catch (SQLException e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); } } catch (Exception e) { dropTables(table); e.printStackTrace(); - } - finally { + } finally { dropTables(table); } } @@ -327,18 +322,24 @@ private void testMultipleClose(Class streamClass) throws Exception { if (!col.getSqlType().canConvert(streamClass, DBCoercion.GET, con)) continue; } - Object stream = rs.getXXX(i + 1, streamClass); - if (stream == null) { - assertEquals(stream, rs.getObject(i + 1), TestResource.getResource("R_streamNull")); - } else { - // close the stream twice - if (streamClass == DBCharacterStream.class) { - ((Reader) stream).close(); - ((Reader) stream).close(); + + Object stream = null; + try { + stream = rs.getXXX(i + 1, streamClass); + } finally { + if (null == stream) { + assertEquals(stream, rs.getObject(i + 1), TestResource.getResource("R_streamNull")); } else { - ((InputStream) stream).close(); - ((InputStream) stream).close(); + // close the stream twice + if (streamClass == DBCharacterStream.class) { + ((Reader) stream).close(); + ((Reader) stream).close(); + } else { + ((InputStream) stream).close(); + ((InputStream) stream).close(); + } } + } } } @@ -397,7 +398,6 @@ private void testLobsInsertRetrieve(String types[], Class lobClass) throws Excep Clob clob = null; Blob blob = null; NClob nclob = null; - InputStream stream = null; try (PreparedStatement ps = conn .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { if (clobType == classType(lobClass)) { @@ -433,24 +433,27 @@ private void testLobsInsertRetrieve(String types[], Class lobClass) throws Excep clob = conn.createClob(); clob.setString(1, stringData); rs.getClob(2); - stream = clob.getAsciiStream(); - assertEquals(clob.length(), size); + try (InputStream stream = clob.getAsciiStream()) { + assertEquals(clob.length(), size); + } } else if (nClobType == classType(lobClass)) { nclob = rs.getNClob(2); assertEquals(nclob.length(), size); - stream = nclob.getAsciiStream(); - BufferedInputStream is = new BufferedInputStream(stream); - is.read(chunk); - assertEquals(chunk.length, size); + try (InputStream stream = nclob.getAsciiStream(); + BufferedInputStream is = new BufferedInputStream(stream)) { + is.read(chunk); + assertEquals(chunk.length, size); + } } else { blob = rs.getBlob(2); - stream = blob.getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + try (InputStream stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } } } @@ -498,7 +501,6 @@ public void readBlobStreamAfterClosingRS() throws Exception { ThreadLocalRandom.current().nextBytes(data); Blob blob = null; - InputStream stream = null; try (PreparedStatement ps = conn .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { blob = conn.createBlob(); @@ -513,19 +515,21 @@ public void readBlobStreamAfterClosingRS() throws Exception { rs.next(); blob = rs.getBlob(2); - stream = blob.getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); - rs.close(); - stream = blob.getBinaryStream(); - buffer = new ByteArrayOutputStream(); - read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + try (InputStream stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + rs.close(); + } + try (InputStream stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } } } finally { if (null != blob) @@ -556,7 +560,7 @@ public void readMultipleBlobStreamsThenCloseRS() throws Exception { ps.executeUpdate(); } } - + byte[] chunk = new byte[size]; try (ResultSet rs = stmt.executeQuery( "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0))) { @@ -564,20 +568,27 @@ public void readMultipleBlobStreamsThenCloseRS() throws Exception { rs.next(); blobs[i] = rs.getBlob(2); stream = blobs[i].getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } + } + + for (int i = 0; i < 5; i++) { + stream = blobs[i].getBinaryStream(); + try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } + } + } finally { + if (null != stream) { + stream.close(); } - } - for (int i = 0; i < 5; i++) { - stream = blobs[i].getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); } }