diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/BulkCopySendTemporalDataTypesAsStringAETest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/BulkCopySendTemporalDataTypesAsStringAETest.java index 6dd177ab57..0ab4726cdc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/BulkCopySendTemporalDataTypesAsStringAETest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/BulkCopySendTemporalDataTypesAsStringAETest.java @@ -167,7 +167,9 @@ public static void setupTest() throws SQLException { @AfterAll public static void cleanTest() throws SQLException { - try (Connection con = getConnection(); Statement stmt = con.createStatement()) { + // Make sure to clean objects against the AE connection string, not the common connection + try (Connection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(destTableNameAE, stmt); } } 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 fbda542591..1a561dda6f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -9,10 +9,10 @@ import static org.junit.jupiter.api.Assertions.fail; import java.math.BigDecimal; +import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; -import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -160,8 +160,9 @@ public static void initValues() throws Exception { @AfterAll public static void dropAll() throws Exception { - dropTables(); + // Drop procedures before tables or table drop will fail dropProcedures(); + dropTables(); } @ParameterizedTest diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/EnclaveTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/EnclaveTest.java index 43dc7ed66b..aa9f28a159 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/EnclaveTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/EnclaveTest.java @@ -4,8 +4,8 @@ */ package com.microsoft.sqlserver.jdbc.AlwaysEncrypted; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Connection; import java.sql.DriverManager; @@ -347,8 +347,12 @@ public void testChar(String serverName, String url, String protocol) throws Exce SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { TestUtils.dropTableIfExists(CHAR_TABLE_AE, stmt); createTable(CHAR_TABLE_AE, cekJks, charTable); - populateCharNormalCase(createCharValues(false)); - testAlterColumnEncryption(stmt, CHAR_TABLE_AE, charTable, cekJks); + try { + populateCharNormalCase(createCharValues(false)); + testAlterColumnEncryption(stmt, CHAR_TABLE_AE, charTable, cekJks); + } finally { + TestUtils.dropTableIfExists(CHAR_TABLE_AE, stmt); + } } } @@ -364,8 +368,12 @@ public void testCharAkv(String serverName, String url, String protocol) throws E SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { TestUtils.dropTableIfExists(CHAR_TABLE_AE, stmt); createTable(CHAR_TABLE_AE, cekAkv, charTable); - populateCharNormalCase(createCharValues(false)); - testAlterColumnEncryption(stmt, CHAR_TABLE_AE, charTable, cekAkv); + try { + populateCharNormalCase(createCharValues(false)); + testAlterColumnEncryption(stmt, CHAR_TABLE_AE, charTable, cekAkv); + } finally { + TestUtils.dropTableIfExists(CHAR_TABLE_AE, connection.createStatement()); + } } } @@ -387,6 +395,8 @@ public void testAEFMTOnly(String serverName, String url, String protocol) throws try (PreparedStatement p = c.prepareStatement(sql)) { ParameterMetaData pmd = p.getParameterMetaData(); assertTrue(48 == pmd.getParameterCount(), "parameter count: " + pmd.getParameterCount()); + } finally { + TestUtils.dropTableIfExists(NUMERIC_TABLE_AE, s); } } } @@ -401,14 +411,18 @@ public void testAlter(String serverName, String url, String protocol) throws Exc try (SQLServerConnection c = PrepUtil.getConnection(AETestConnectionString, AEInfo); Statement s = c.createStatement()) { createTable(CHAR_TABLE_AE, cekJks, varcharTableSimple); - PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + CHAR_TABLE_AE + " VALUES (?,?,?)"); - pstmt.setString(1, "a"); - pstmt.setString(2, "b"); - pstmt.setString(3, "test"); - pstmt.execute(); - pstmt = c.prepareStatement("ALTER TABLE " + CHAR_TABLE_AE - + " ALTER COLUMN RandomizedVarchar VARCHAR(20) NULL WITH (ONLINE = ON)"); - pstmt.execute(); + try { + PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + CHAR_TABLE_AE + " VALUES (?,?,?)"); + pstmt.setString(1, "a"); + pstmt.setString(2, "b"); + pstmt.setString(3, "test"); + pstmt.execute(); + pstmt = c.prepareStatement("ALTER TABLE " + CHAR_TABLE_AE + + " ALTER COLUMN RandomizedVarchar VARCHAR(20) NULL WITH (ONLINE = ON)"); + pstmt.execute(); + } finally { + TestUtils.dropTableIfExists(CHAR_TABLE_AE, s); + } } } @@ -422,19 +436,23 @@ public void testNumericRichQuery(String serverName, String url, String protocol) try (SQLServerConnection c = PrepUtil.getConnection(AETestConnectionString, AEInfo); Statement s = c.createStatement()) { createTable(NUMERIC_TABLE_AE, cekJks, numericTableSimple); - PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + NUMERIC_TABLE_AE + " VALUES (?,?,?)"); - pstmt.setInt(1, 1); - pstmt.setInt(2, 2); - pstmt.setInt(3, 3); - pstmt.execute(); - pstmt = c.prepareStatement("SELECT * FROM " + NUMERIC_TABLE_AE + " WHERE RANDOMIZEDInt = ?"); - pstmt.setInt(1, 3); - try (ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - assertTrue(1 == rs.getInt(1), "rs.getInt(1)=" + rs.getInt(1)); - assertTrue(2 == rs.getInt(2), "rs.getInt(2)=" + rs.getInt(2)); - assertTrue(3 == rs.getInt(3), "rs.getInt(3)=" + rs.getInt(3)); + try { + PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + NUMERIC_TABLE_AE + " VALUES (?,?,?)"); + pstmt.setInt(1, 1); + pstmt.setInt(2, 2); + pstmt.setInt(3, 3); + pstmt.execute(); + pstmt = c.prepareStatement("SELECT * FROM " + NUMERIC_TABLE_AE + " WHERE RANDOMIZEDInt = ?"); + pstmt.setInt(1, 3); + try (ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + assertTrue(1 == rs.getInt(1), "rs.getInt(1)=" + rs.getInt(1)); + assertTrue(2 == rs.getInt(2), "rs.getInt(2)=" + rs.getInt(2)); + assertTrue(3 == rs.getInt(3), "rs.getInt(3)=" + rs.getInt(3)); + } } + } finally { + TestUtils.dropTableIfExists(NUMERIC_TABLE_AE, s); } } } @@ -449,20 +467,23 @@ public void testStringRichQuery(String serverName, String url, String protocol) try (SQLServerConnection c = PrepUtil.getConnection(AETestConnectionString, AEInfo); Statement s = c.createStatement()) { createTable(CHAR_TABLE_AE, cekJks, varcharTableSimple); - - PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + CHAR_TABLE_AE + " VALUES (?,?,?)"); - pstmt.setString(1, "a"); - pstmt.setString(2, "b"); - pstmt.setString(3, "test"); - pstmt.execute(); - pstmt = c.prepareStatement("SELECT * FROM " + CHAR_TABLE_AE + " WHERE RANDOMIZEDVarchar LIKE ?"); - pstmt.setString(1, "t%"); - try (ResultSet rs = pstmt.executeQuery()) { - while (rs.next()) { - assertTrue(rs.getString(1).equalsIgnoreCase("a"), "rs.getString(1)=" + rs.getString(1)); - assertTrue(rs.getString(2).equalsIgnoreCase("b"), "rs.getString(2)=" + rs.getString(2)); - assertTrue(rs.getString(3).equalsIgnoreCase("test"), "rs.getString(3)=" + rs.getString(3)); + try { + PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + CHAR_TABLE_AE + " VALUES (?,?,?)"); + pstmt.setString(1, "a"); + pstmt.setString(2, "b"); + pstmt.setString(3, "test"); + pstmt.execute(); + pstmt = c.prepareStatement("SELECT * FROM " + CHAR_TABLE_AE + " WHERE RANDOMIZEDVarchar LIKE ?"); + pstmt.setString(1, "t%"); + try (ResultSet rs = pstmt.executeQuery()) { + while (rs.next()) { + assertTrue(rs.getString(1).equalsIgnoreCase("a"), "rs.getString(1)=" + rs.getString(1)); + assertTrue(rs.getString(2).equalsIgnoreCase("b"), "rs.getString(2)=" + rs.getString(2)); + assertTrue(rs.getString(3).equalsIgnoreCase("test"), "rs.getString(3)=" + rs.getString(3)); + } } + } finally { + TestUtils.dropTableIfExists(CHAR_TABLE_AE, s); } } } @@ -477,27 +498,36 @@ public void testAlterNoEncrypt(String serverName, String url, String protocol) t try (SQLServerConnection c = PrepUtil.getConnection(AETestConnectionString, AEInfo); Statement s = c.createStatement()) { createTable(CHAR_TABLE_AE, cekJks, varcharTableSimple); - PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + CHAR_TABLE_AE + " VALUES (?,?,?)"); - pstmt.setString(1, "a"); - pstmt.setString(2, "b"); - pstmt.setString(3, "test"); - pstmt.execute(); - } - String testConnectionString = TestUtils.removeProperty(AETestConnectionString, - Constants.ENCLAVE_ATTESTATIONURL); - testConnectionString = TestUtils.removeProperty(testConnectionString, Constants.ENCLAVE_ATTESTATIONPROTOCOL); - try (Connection c = DriverManager.getConnection(testConnectionString)) { - PreparedStatement pstmt = c.prepareStatement("ALTER TABLE " + CHAR_TABLE_AE - + " ALTER COLUMN RandomizedVarchar VARCHAR(20) NULL WITH (ONLINE = ON)"); - pstmt.execute(); - } catch (SQLException e) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_enclaveNotEnabled")), e.getMessage()); + try { + PreparedStatement pstmt = c.prepareStatement("INSERT INTO " + CHAR_TABLE_AE + " VALUES (?,?,?)"); + pstmt.setString(1, "a"); + pstmt.setString(2, "b"); + pstmt.setString(3, "test"); + pstmt.execute(); + + String testConnectionString = TestUtils.removeProperty(AETestConnectionString, + Constants.ENCLAVE_ATTESTATIONURL); + testConnectionString = TestUtils.removeProperty(testConnectionString, + Constants.ENCLAVE_ATTESTATIONPROTOCOL); + try (Connection c1 = DriverManager.getConnection(testConnectionString)) { + PreparedStatement pstmt1 = c1.prepareStatement("ALTER TABLE " + CHAR_TABLE_AE + + " ALTER COLUMN RandomizedVarchar VARCHAR(20) NULL WITH (ONLINE = ON)"); + pstmt1.execute(); + } catch (SQLException e) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_enclaveNotEnabled")), + e.getMessage()); + } + } finally { + TestUtils.dropTableIfExists(CHAR_TABLE_AE, s); + } } } @AfterAll public static void dropAll() throws Exception { - try (Statement stmt = connection.createStatement()) { + // Make sure to clean objects against the AE connection string, not the common connection + try (SQLServerConnection cn = PrepUtil.getConnection(AETestConnectionString, AEInfo); + Statement stmt = cn.createStatement()) { TestUtils.dropTableIfExists(CHAR_TABLE_AE, stmt); TestUtils.dropTableIfExists(NUMERIC_TABLE_AE, stmt); TestUtils.dropTableIfExists(BINARY_TABLE_AE, stmt); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MSITest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MSITest.java index ee4c2707ee..6cb180d49f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MSITest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/MSITest.java @@ -16,16 +16,15 @@ import java.util.Map; import java.util.Properties; -import com.azure.identity.CredentialUnavailableException; -import com.azure.identity.ManagedIdentityCredential; -import com.azure.identity.ManagedIdentityCredentialBuilder; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.azure.identity.CredentialUnavailableException; +import com.azure.identity.ManagedIdentityCredential; +import com.azure.identity.ManagedIdentityCredentialBuilder; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerConnection; @@ -454,6 +453,8 @@ private void testNumericAKV(String connStr) throws SQLException { AECommon.testGetBigDecimal(rs, numberOfColumns, values); AECommon.testWithSpecifiedtype(rs, numberOfColumns, values); } + } finally { + TestUtils.dropTableIfExists(NUMERIC_TABLE_AE, stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java index 0fbdfda5b9..5948ccbbbc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java @@ -311,5 +311,6 @@ public static void dropTables(Statement stmt) throws SQLException { TestUtils.dropTableIfExists(DATE_TABLE_AE, stmt); TestUtils.dropTableIfExists(CHAR_TABLE_AE, stmt); TestUtils.dropTableIfExists(NUMERIC_TABLE_AE, stmt); + TestUtils.dropTableIfExists(VARY_STRING_TABLE_AE, stmt); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java index 060c7648d7..07df43e8f7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java @@ -507,8 +507,10 @@ public static void dropTypeIfExists(String typeName, java.sql.Statement stmt) th * @throws SQLException */ public static void dropUserDefinedTypeIfExists(String typeName, Statement stmt) throws SQLException { - stmt.executeUpdate("IF EXISTS (select * from sys.types where name = '" + escapeSingleQuotes(typeName) - + "') DROP TYPE " + typeName); + String input = AbstractSQLGenerator.unEscapeIdentifier(typeName); + String sql = "IF EXISTS (select * from sys.types where name = '" + escapeSingleQuotes(input) + "') DROP TYPE " + + AbstractSQLGenerator.escapeIdentifier(input); + stmt.executeUpdate(sql); } /** 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 584964ee9d..11a9d2fc66 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java @@ -102,7 +102,7 @@ public static void setUpConnection() throws Exception { */ @Test @DisplayName("Test SQLServerBulkCSVFileRecord") - public void testCSV() { + public void testCSV() throws Exception { String fileName = filePath + inputFile; try (SQLServerBulkCSVFileRecord f1 = new SQLServerBulkCSVFileRecord(fileName, encoding, delimiter, true); SQLServerBulkCSVFileRecord f2 = new SQLServerBulkCSVFileRecord(fileName, encoding, delimiter, true);) { @@ -110,8 +110,6 @@ public void testCSV() { f2.setEscapeColumnDelimitersCSV(true); testBulkCopyCSV(f2, true); - } catch (SQLException e) { - fail(e.getMessage()); } } @@ -120,7 +118,7 @@ public void testCSV() { */ @Test @DisplayName("Test SQLServerBulkCSVFileRecord First line not being column name") - public void testCSVFirstLineNotColumnName() { + public void testCSVFirstLineNotColumnName() throws Exception { String fileName = filePath + inputFileNoColumnName; try (SQLServerBulkCSVFileRecord f1 = new SQLServerBulkCSVFileRecord(fileName, encoding, delimiter, false); SQLServerBulkCSVFileRecord f2 = new SQLServerBulkCSVFileRecord(fileName, encoding, delimiter, false)) { @@ -128,8 +126,6 @@ public void testCSVFirstLineNotColumnName() { f2.setEscapeColumnDelimitersCSV(true); testBulkCopyCSV(f2, false); - } catch (SQLException e) { - fail(e.getMessage()); } } @@ -140,15 +136,13 @@ public void testCSVFirstLineNotColumnName() { */ @Test @DisplayName("Test SQLServerBulkCSVFileRecord with passing file from url") - public void testCSVFromURL() throws SQLException { + public void testCSVFromURL() throws Exception { try (InputStream csvFileInputStream = new URL( "https://raw.githubusercontent.com/Microsoft/mssql-jdbc/master/src/test/resources/BulkCopyCSVTestInput.csv") .openStream(); SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(csvFileInputStream, encoding, delimiter, true)) { testBulkCopyCSV(fileRecord, true); - } catch (Exception e) { - fail(e.getMessage()); } } @@ -210,8 +204,10 @@ public void testEscapeColumnDelimitersCSV() throws Exception { } assertEquals(i, 12, "Expected to load 12 records, but loaded " + i + " records"); } - - TestUtils.dropTableIfExists(tableName, stmt); + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(tableName, stmt); + } } } @@ -278,7 +274,7 @@ public void testEscapeColumnDelimitersCSVNoNewLineAtEnd() throws Exception { */ @Test @DisplayName("Test SQLServerBulkCSVFileRecord GitHb 1391") - public void testCSV1391() { + public void testCSV1391() throws Exception { String fileName = filePath + inputFile; try (SQLServerBulkCSVFileRecord f1 = new BulkData1391(fileName, encoding, delimiter, true); SQLServerBulkCSVFileRecord f2 = new BulkData1391(fileName, encoding, delimiter, true);) { @@ -286,8 +282,6 @@ public void testCSV1391() { f2.setEscapeColumnDelimitersCSV(true); testBulkCopyCSV(f2, true); - } catch (SQLException e) { - fail(e.getMessage()); } } @@ -309,7 +303,8 @@ public Set getColumnOrdinals() { } } - private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, boolean firstLineIsColumnNames) { + private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, + boolean firstLineIsColumnNames) throws Exception { DBTable destTable = null; try (BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { @@ -363,8 +358,6 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, boolean firs else validateValuesFromCSV(destTable, inputFileNoColumnName); - } catch (Exception e) { - fail(e.getMessage()); } finally { if (null != destTable) { stmt.dropTable(destTable); @@ -377,7 +370,7 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, boolean firs * * @param destinationTable */ - static void validateValuesFromCSV(DBTable destinationTable, String inputFile) { + static void validateValuesFromCSV(DBTable destinationTable, String inputFile) throws Exception { try (BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { if (inputFile.equalsIgnoreCase("BulkCopyCSVTestInput.csv")) @@ -403,8 +396,6 @@ static void validateValuesFromCSV(DBTable destinationTable, String inputFile) { } } } - } catch (Exception e) { - fail("CSV validation failed with " + e.getMessage()); } } @@ -415,7 +406,7 @@ static void validateValuesFromCSV(DBTable destinationTable, String inputFile) { */ @Test @DisplayName("Test SQLServerBulkCSVFileRecord GitHb 2400") - public void testCSV2400() { + public void testCSV2400() throws Exception { String tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("BulkEscape")); String fileName = filePath + inputFileMultipleDoubleQuotes; @@ -449,10 +440,6 @@ public void testCSV2400() { bulkCopy.writeToServer(fileRecord); TestUtils.dropTableIfExists(tableName, stmt); - } catch (StackOverflowError e) { - fail("Stack overflow: " + e.getMessage()); - } catch (SQLException e) { - fail("SQL exception: " + e.getMessage()); } } @@ -507,7 +494,9 @@ public void testBulkCopyWithJson() throws Exception { } i++; } - } finally { + } + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); } } @@ -518,7 +507,7 @@ public void testBulkCopyWithJson() throws Exception { */ @Test @DisplayName("Test bulk copy with computed column as last column") - public void testBulkCopyWithComputedColumnAsLastColumn() { + public void testBulkCopyWithComputedColumnAsLastColumn() throws SQLException { String tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("BulkEscape")); String fileName = filePath + computeColumnCsvFile; @@ -555,11 +544,11 @@ public void testBulkCopyWithComputedColumnAsLastColumn() { int rowCount = rs.getInt(1); assertTrue(rowCount > 0); } - } finally { + } + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); } - } catch (Exception e) { - fail(e.getMessage()); } } @@ -568,7 +557,7 @@ public void testBulkCopyWithComputedColumnAsLastColumn() { */ @Test @DisplayName("Test bulk copy with computed column not as last column") - public void testBulkCopyWithComputedColumnNotAsLastColumn() { + public void testBulkCopyWithComputedColumnNotAsLastColumn() throws SQLException { String tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("BulkEscape")); String fileName = filePath + computeColumnCsvFile; @@ -607,11 +596,11 @@ public void testBulkCopyWithComputedColumnNotAsLastColumn() { int rowCount = rs.getInt(1); assertTrue(rowCount > 0); } - } finally { + } + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); } - } catch (Exception e) { - fail(e.getMessage()); } } @@ -622,7 +611,7 @@ public void testBulkCopyWithComputedColumnNotAsLastColumn() { @Test @Tag(Constants.vectorTest) public void testBulkCopyVectorFromCSV() throws SQLException { - String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable")); + String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyVectorCsv")); String fileName = filePath + vectorInputCsvFile; try (Connection con = getConnection(); @@ -684,11 +673,11 @@ public void testBulkCopyVectorFromCSV() throws SQLException { // Validate row count assertEquals(expectedData.size(), rowCount, "Row count mismatch."); - } finally { + } + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(dstTable, stmt); } - } catch (Exception e) { - fail(e.getMessage()); } } @@ -699,7 +688,7 @@ public void testBulkCopyVectorFromCSV() throws SQLException { @Test @Tag(Constants.vectorTest) public void testBulkCopyVectorFromCSVWithMultipleColumns() throws SQLException { - String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable")); + String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableVectorCsvMulti")); String fileName = filePath + vectorInputCsvFileWithMultipleColumn; try (Connection con = getConnection(); @@ -751,11 +740,11 @@ public void testBulkCopyVectorFromCSVWithMultipleColumns() throws SQLException { // Validate row count assertEquals(expectedData.size(), rowCount, "Row count mismatch."); - } finally { + } + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(dstTable, stmt); } - } catch (Exception e) { - fail(e.getMessage()); } } @@ -766,7 +755,7 @@ public void testBulkCopyVectorFromCSVWithMultipleColumns() throws SQLException { @Test @Tag(Constants.vectorTest) public void testBulkCopyVectorFromCSVWithMultipleColumnsWithPipeDelimiter() throws SQLException { - String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable")); + String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyVectorCsvMultiPipe")); String fileName = filePath + vectorInputCsvFileWithMultipleColumnWithPipeDelimiter; try (Connection con = getConnection(); @@ -818,11 +807,11 @@ public void testBulkCopyVectorFromCSVWithMultipleColumnsWithPipeDelimiter() thro // Validate row count assertEquals(expectedData.size(), rowCount, "Row count mismatch."); - } finally { + } + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(dstTable, stmt); } - } catch (Exception e) { - fail(e.getMessage()); } } @@ -833,7 +822,7 @@ public void testBulkCopyVectorFromCSVWithMultipleColumnsWithPipeDelimiter() thro @Test @Tag(Constants.vectorTest) public void testBulkCopyVectorFromCSVWithIncorrectDimension() throws SQLException { - String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable")); + String dstTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyVectorCsvBadDim")); String fileName = filePath + vectorInputCsvFile; try (Connection con = getConnection(); @@ -867,6 +856,10 @@ public void testBulkCopyVectorFromCSVWithIncorrectDimension() throws SQLExceptio } catch (SQLException e) { assertTrue(e.getMessage().contains("The vector dimensions 4 and 3 do not match."), "Unexpected error message: " + e.getMessage()); + } finally { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(dstTable, stmt); + } } } 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 11edbc9542..ca34bb5d51 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java @@ -89,7 +89,7 @@ public void testISQLServerBulkRecord() throws SQLException { @Test public void testBulkCopyDateTimePrecision() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyDt"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { @@ -164,7 +164,7 @@ public void testBulkCopyDateTimePrecision() throws SQLException { @Tag(Constants.vectorTest) public void testBulkCopyVector() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyVector"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -202,7 +202,7 @@ public void testBulkCopyVector() throws SQLException { @Tag(Constants.JSONTest) public void testBulkCopyJSON() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -236,7 +236,7 @@ public void testBulkCopyJSON() throws SQLException { @Tag(Constants.JSONTest) public void testBulkCopyWithEmptyJsonDocument() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyEmptyJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -275,7 +275,7 @@ public void testBulkCopyWithEmptyJsonDocument() throws SQLException { @Tag(Constants.JSONTest) public void testBulkCopyMultipleJsonRowsWithDifferentStructures() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyMulti"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -317,7 +317,7 @@ public void testBulkCopyMultipleJsonRowsWithDifferentStructures() throws SQLExce @Tag(Constants.JSONTest) public void testBulkCopyMultipleJsonRows() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyMulti"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -359,7 +359,7 @@ public void testBulkCopyMultipleJsonRows() throws SQLException { @Tag(Constants.JSONTest) public void testBulkCopyMultipleJsonRowsAndColumns() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyMulti"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -460,7 +460,7 @@ public void testBulkCopyWithSendStringParametersAsUnicode() throws SQLException @Tag(Constants.JSONTest) public void testBulkCopyNestedJsonRows() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyNested"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -502,7 +502,7 @@ public void testBulkCopyNestedJsonRows() throws SQLException { @Tag(Constants.JSONTest) public void testBulkCopyWithVariousDataTypes() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyVarious"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -540,7 +540,7 @@ public void testBulkCopyWithVariousDataTypes() throws SQLException { @Tag(Constants.JSONTest) public void testBulkCopyWithCountVerification() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyCount"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -664,7 +664,7 @@ private static Object[] parseJsonArrayToFloatArray(String json) { @Tag(Constants.vectorTest) public void testBulkCopyVectorNull() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableBulkCopyVectorNull"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement(); @@ -692,8 +692,6 @@ public void testBulkCopyVectorNull() throws SQLException { assertEquals(1, rowCount, "Row count mismatch after inserting null vector data."); } - } catch (Exception e) { - fail(e.getMessage()); } finally { try (Statement stmt = conn.createStatement();) { TestUtils.dropTableIfExists(dstTable, stmt); 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 71cdd61cd9..1f41a48464 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -14,15 +14,14 @@ import java.sql.Statement; import java.sql.Types; import java.text.MessageFormat; -import java.time.OffsetDateTime; -import java.time.OffsetTime; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.OffsetTime; import java.util.TimeZone; import java.util.UUID; -import com.microsoft.sqlserver.testframework.PrepUtil; import org.junit.Assert; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -39,6 +38,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; /** @@ -90,7 +90,7 @@ public static void setupTest() throws Exception { setConnection(); try (Statement stmt = connection.createStatement()) { - TestUtils.dropTableIfExists(tableNameGUID, stmt); + // Drop order matters. Can't drop objects still referenced by other objects. TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); @@ -99,11 +99,12 @@ public static void setupTest() throws Exception { TestUtils.dropProcedureIfExists(conditionalSproc, stmt); TestUtils.dropProcedureIfExists(simpleRetValSproc, stmt); TestUtils.dropProcedureIfExists(zeroParamSproc, stmt); - TestUtils.dropUserDefinedTypeIfExists(manyParamUserDefinedType, stmt); TestUtils.dropProcedureIfExists(manyParamProc, stmt); + TestUtils.dropProcedureIfExists(procedureNameJSON, stmt); + TestUtils.dropTableIfExists(tableNameGUID, stmt); TestUtils.dropTableIfExists(manyParamsTable, stmt); TestUtils.dropTableIfExists(tableNameJSON, stmt); - TestUtils.dropProcedureIfExists(procedureNameJSON, stmt); + TestUtils.dropUserDefinedTypeIfExists(manyParamUserDefinedType, stmt); createGUIDTable(stmt); createGUIDStoredProcedure(stmt); @@ -186,6 +187,8 @@ public void testCallableStatementSpPrepare() throws SQLException { rs.next(); assertEquals(1, rs.getInt(1), TestResource.getResource("R_setDataNotEqual")); } + } finally { + TestUtils.dropProcedureIfExists(procName, statement); } } } @@ -522,74 +525,81 @@ public void testCallableStatementSetByAnnotatedArgs() throws SQLException { @Tag(Constants.xAzureSQLDW) @Tag(Constants.xAzureSQLMI) public void testFourPartSyntaxCallEscapeSyntax() throws SQLException { - String table = "serverList"; + String table = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("serverList")); + try { - try (Statement stmt = connection.createStatement()) { - stmt.execute("IF OBJECT_ID(N'" + table + "') IS NOT NULL DROP TABLE " + table); - stmt.execute("CREATE TABLE " + table - + " (serverName varchar(100),network varchar(100),serverStatus varchar(4000), id int, collation varchar(100), connectTimeout int, queryTimeout int)"); - stmt.execute("INSERT " + table + " EXEC sp_helpserver"); + try (Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(table, stmt); + stmt.execute("CREATE TABLE " + table + + " (serverName varchar(100),network varchar(100),serverStatus varchar(4000), id int, collation varchar(100), connectTimeout int, queryTimeout int)"); + stmt.execute("INSERT " + table + " EXEC sp_helpserver"); - ResultSet rs = stmt - .executeQuery("SELECT COUNT(*) FROM " + table + " WHERE serverName = N'" + linkedServer + "'"); - rs.next(); + ResultSet rs = stmt + .executeQuery("SELECT COUNT(*) FROM " + table + " WHERE serverName = N'" + linkedServer + "'"); + rs.next(); + + if (rs.getInt(1) == 1) { + stmt.execute("EXEC sp_dropserver @server='" + linkedServer + "';"); + } - if (rs.getInt(1) == 1) { - stmt.execute("EXEC sp_dropserver @server='" + linkedServer + "';"); + stmt.execute("EXEC sp_addlinkedserver @server='" + linkedServer + "';"); + stmt.execute("EXEC sp_addlinkedsrvlogin @rmtsrvname=N'" + linkedServer + "', @useself=false" + + ", @rmtuser=N'" + linkedServerUser + "', @rmtpassword=N'" + linkedServerPassword + "'"); + stmt.execute("EXEC sp_serveroption '" + linkedServer + "', 'rpc', true;"); + stmt.execute("EXEC sp_serveroption '" + linkedServer + "', 'rpc out', true;"); } - stmt.execute("EXEC sp_addlinkedserver @server='" + linkedServer + "';"); - stmt.execute("EXEC sp_addlinkedsrvlogin @rmtsrvname=N'" + linkedServer + "', @useself=false" - + ", @rmtuser=N'" + linkedServerUser + "', @rmtpassword=N'" + linkedServerPassword + "'"); - stmt.execute("EXEC sp_serveroption '" + linkedServer + "', 'rpc', true;"); - stmt.execute("EXEC sp_serveroption '" + linkedServer + "', 'rpc out', true;"); - } + SQLServerDataSource ds = new SQLServerDataSource(); + ds.setServerName(linkedServer); + ds.setUser(linkedServerUser); + ds.setPassword(linkedServerPassword); + ds.setEncrypt(false); + ds.setTrustServerCertificate(true); - SQLServerDataSource ds = new SQLServerDataSource(); - ds.setServerName(linkedServer); - ds.setUser(linkedServerUser); - ds.setPassword(linkedServerPassword); - ds.setEncrypt(false); - ds.setTrustServerCertificate(true); - - try (Connection linkedServerConnection = ds.getConnection(); - Statement stmt = linkedServerConnection.createStatement()) { - stmt.execute( - "create or alter procedure dbo.TestAdd(@Num1 int, @Num2 int, @Result int output) as begin set @Result = @Num1 + @Num2; end;"); - - stmt.execute("create or alter procedure dbo.TestReturn(@Num1 int) as select @Num1 return @Num1*3 "); - } + try (Connection linkedServerConnection = ds.getConnection(); + Statement stmt = linkedServerConnection.createStatement()) { + stmt.execute( + "create or alter procedure dbo.TestAdd(@Num1 int, @Num2 int, @Result int output) as begin set @Result = @Num1 + @Num2; end;"); - try (CallableStatement cstmt = connection - .prepareCall("{call [" + linkedServer + "].master.dbo.TestAdd(?,?,?)}")) { - int sum = 11; - int param0 = 1; - int param1 = 10; - cstmt.setInt(1, param0); - cstmt.setInt(2, param1); - cstmt.registerOutParameter(3, Types.INTEGER); - cstmt.execute(); - assertEquals(sum, cstmt.getInt(3)); - } + stmt.execute("create or alter procedure dbo.TestReturn(@Num1 int) as select @Num1 return @Num1*3 "); + } - try (CallableStatement cstmt = connection.prepareCall("exec [" + linkedServer + "].master.dbo.TestAdd ?,?,?")) { - int sum = 11; - int param0 = 1; - int param1 = 10; - cstmt.setInt(1, param0); - cstmt.setInt(2, param1); - cstmt.registerOutParameter(3, Types.INTEGER); - cstmt.execute(); - assertEquals(sum, cstmt.getInt(3)); - } + try (CallableStatement cstmt = connection + .prepareCall("{call [" + linkedServer + "].master.dbo.TestAdd(?,?,?)}")) { + int sum = 11; + int param0 = 1; + int param1 = 10; + cstmt.setInt(1, param0); + cstmt.setInt(2, param1); + cstmt.registerOutParameter(3, Types.INTEGER); + cstmt.execute(); + assertEquals(sum, cstmt.getInt(3)); + } - try (CallableStatement cstmt = connection - .prepareCall("{? = call [" + linkedServer + "].master.dbo.TestReturn(?)}")) { - int expected = 15; - cstmt.registerOutParameter(1, java.sql.Types.INTEGER); - cstmt.setInt(2, 5); - cstmt.execute(); - assertEquals(expected, cstmt.getInt(1)); + try (CallableStatement cstmt = connection + .prepareCall("exec [" + linkedServer + "].master.dbo.TestAdd ?,?,?")) { + int sum = 11; + int param0 = 1; + int param1 = 10; + cstmt.setInt(1, param0); + cstmt.setInt(2, param1); + cstmt.registerOutParameter(3, Types.INTEGER); + cstmt.execute(); + assertEquals(sum, cstmt.getInt(3)); + } + + try (CallableStatement cstmt = connection + .prepareCall("{? = call [" + linkedServer + "].master.dbo.TestReturn(?)}")) { + int expected = 15; + cstmt.registerOutParameter(1, java.sql.Types.INTEGER); + cstmt.setInt(2, 5); + cstmt.execute(); + assertEquals(expected, cstmt.getInt(1)); + } + } finally { + try (Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(table, stmt); + } } } @@ -657,8 +667,7 @@ public void testJSONProcedureWithSetObject() throws SQLException { @AfterAll public static void cleanup() throws SQLException { try (Statement stmt = connection.createStatement()) { - TestUtils.dropTableIfExists(tableNameGUID, stmt); - TestUtils.dropTableIfExists(manyParamsTable, stmt); + // Drop order matters. Can't drop objects still referenced by other objects. TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); @@ -668,8 +677,12 @@ public static void cleanup() throws SQLException { TestUtils.dropProcedureIfExists(conditionalSproc, stmt); TestUtils.dropProcedureIfExists(simpleRetValSproc, stmt); TestUtils.dropProcedureIfExists(zeroParamSproc, stmt); + TestUtils.dropProcedureIfExists(procedureNameJSON, stmt); + TestUtils.dropProcedureIfExists(manyParamProc, stmt); + TestUtils.dropTableIfExists(tableNameGUID, stmt); + TestUtils.dropTableIfExists(manyParamsTable, stmt); TestUtils.dropTableIfExists(tableNameJSON, stmt); - TestUtils.dropProcedureIfExists(procedureNameJSON, stmt); + TestUtils.dropUserDefinedTypeIfExists(manyParamUserDefinedType, 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 99dbe64dc0..8cb98ab583 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java @@ -4,8 +4,8 @@ */ package com.microsoft.sqlserver.jdbc.datatypes; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Connection; import java.sql.Date; @@ -328,6 +328,9 @@ public void testSetup() throws TestAbortedException, Exception { public static void terminateVariation() throws SQLException { try (Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTypeIfExists(timestampTVP, stmt); + TestUtils.dropTypeIfExists(dateTVP, stmt); + TestUtils.dropTypeIfExists(timeTVP, stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/JSONFunctionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/JSONFunctionTest.java index 49d6661072..3a28246cb8 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/JSONFunctionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/JSONFunctionTest.java @@ -30,12 +30,12 @@ import java.sql.SQLException; import java.sql.Statement; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; -import org.junit.jupiter.api.Tag; import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; @@ -64,7 +64,7 @@ public static void setupTests() throws Exception { @Tag(Constants.JSONTest) public void testISJSON() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -101,7 +101,7 @@ public void testISJSON() throws SQLException { @Tag(Constants.JSONTest) public void testISJSONWithVariousInputs() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement stmt = conn.createStatement()) { @@ -152,7 +152,7 @@ public void testISJSONWithVariousInputs() throws SQLException { @Tag(Constants.JSONTest) public void testJSONArrayWithoutNulls() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -185,7 +185,7 @@ public void testJSONArrayWithoutNulls() throws SQLException { @Tag(Constants.JSONTest) public void testJSONArrayWithNulls() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -219,7 +219,7 @@ public void testJSONArrayWithNulls() throws SQLException { @Tag(Constants.JSONTest) public void testJSONArrayWithMixedElements() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -252,7 +252,7 @@ public void testJSONArrayWithMixedElements() throws SQLException { @Tag(Constants.JSONTest) public void testJSONArrayWithVariablesAndExpressions() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -291,7 +291,7 @@ public void testJSONArrayWithVariablesAndExpressions() throws SQLException { @Tag(Constants.JSONTest) public void testJSONArrayPerRow() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -332,7 +332,7 @@ public void testJSONArrayPerRow() throws SQLException { @Tag(Constants.JSONTest) public void testJSONArrayAgg() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -406,7 +406,7 @@ public void testJSONArrayAggWithOrderedElements() throws SQLException { @Tag(Constants.JSONTest) public void testJSONArrayAggWithTwoColumns() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement stmt = conn.createStatement()) { @@ -458,7 +458,7 @@ public void testJSONArrayAggWithTwoColumns() throws SQLException { @Tag(Constants.JSONTest) public void testJSONModify() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -614,7 +614,7 @@ public void testJSONModifyIncrementValue() throws SQLException { @Tag(Constants.JSONTest) public void testJSONModifyUpdateJsonColumn() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -780,7 +780,7 @@ public void testJSONObjectAggWithThreeProperties() throws SQLException { @Tag(Constants.JSONTest) public void testJSONObjectAggWithColumnNamesAndIDs() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement stmt = conn.createStatement()) { @@ -875,7 +875,7 @@ public void testJSONPathExistsFalse() throws SQLException { @Tag(Constants.JSONTest) public void testJSONQueryFragment() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -922,7 +922,7 @@ public void testJSONQueryFragment() throws SQLException { @Tag(Constants.JSONTest) public void testJSONQueryForJSONClause() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -972,7 +972,7 @@ public void testJSONQueryForJSONClause() throws SQLException { @Tag(Constants.JSONTest) public void testJSONValueInQueryResults() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -1021,7 +1021,7 @@ public void testJSONValueInQueryResults() throws SQLException { @Tag(Constants.JSONTest) public void testJSONValueComputedColumns() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString);) { try (Statement dstStmt = conn.createStatement()) { @@ -1072,7 +1072,7 @@ public void testJSONValueComputedColumns() throws SQLException { @Tag(Constants.JSONTest) public void testOpenJsonParseJson() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString)) { try (Statement dstStmt = conn.createStatement()) { @@ -1112,7 +1112,7 @@ public void testOpenJsonParseJson() throws SQLException { @Tag(Constants.JSONTest) public void testOpenJsonParseNestedJson() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString)) { try (Statement dstStmt = conn.createStatement()) { @@ -1152,7 +1152,7 @@ public void testOpenJsonParseNestedJson() throws SQLException { @Tag(Constants.JSONTest) public void testOpenJsonParseArray() throws SQLException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString)) { try (Statement dstStmt = conn.createStatement()) { @@ -1413,13 +1413,13 @@ public void testJoinQueryWithJsonType() throws SQLException { public void testJsonInputOutputWithUdf() throws SQLException { String personsTable = TestUtils .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("Persons"))); - String udfName = "dbo.GetAgeFromJson"; + String udfName = TestUtils + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("GetAgeFromJson"))); try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(personsTable, stmt); - String dropUdfSQL = "IF OBJECT_ID('" + udfName + "', 'FN') IS NOT NULL DROP FUNCTION " + udfName; - stmt.execute(dropUdfSQL); + TestUtils.dropFunctionIfExists(udfName, stmt); String createUdfSQL = "CREATE FUNCTION " + udfName + " (@json JSON) " + "RETURNS INT " + "AS BEGIN " + @@ -1492,13 +1492,13 @@ public void testJsonInputOutputWithUdf() throws SQLException { public void testUdfReturningJson() throws SQLException { String personsTable = TestUtils .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("Persons"))); - String udfName = "dbo.GetPersonJson"; + String udfName = TestUtils + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("GetPersonJson"))); try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(personsTable, stmt); - String dropUdfSQL = "IF OBJECT_ID('" + udfName + "', 'FN') IS NOT NULL DROP FUNCTION " + udfName; - stmt.execute(dropUdfSQL); + TestUtils.dropFunctionIfExists(udfName, stmt); String createUdfSQL = "CREATE FUNCTION " + udfName + " (@id INT, @name NVARCHAR(100)) " + "RETURNS JSON " + @@ -1551,7 +1551,7 @@ public void testUdfReturningJson() throws SQLException { @Tag(Constants.JSONTest) public void testInsert1GBJson() throws SQLException, IOException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); Path tempFile = Files.createTempFile("json_output", ".json"); @@ -1638,7 +1638,7 @@ private boolean filesAreEqual(Path path1, Path path2) throws IOException { @Tag(Constants.JSONTest) public void testInsertHugeJsonData() throws SQLException, IOException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); Path tempFile = Files.createTempFile("json_output", ".json"); @@ -1694,7 +1694,7 @@ public void testInsertHugeJsonData() throws SQLException, IOException { @Tag(Constants.JSONTest) public void testInsert2GBData() throws SQLException, FileNotFoundException, IOException { String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON"))); try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { @@ -1770,7 +1770,7 @@ public void testJsonStoredProcedureInputOutput() throws SQLException { @Tag(Constants.JSONTest) public void testJSONWithSendStringParameterAsUnicodeFalse() throws SQLException { String dstTable = TestUtils.escapeSingleQuotes( - AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable")) + AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON")) ); String validJson = "{\"key1\":\"value1\"}"; @@ -1807,7 +1807,7 @@ public void testJSONWithSendStringParameterAsUnicodeFalse() throws SQLException @Tag(Constants.JSONTest) public void testJSONWithSendStringParameterAsUnicodeTrue() throws SQLException { String dstTable = TestUtils.escapeSingleQuotes( - AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable")) + AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableJSON")) ); String validJson = "{\"key1\":\"value1\"}"; diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/VectorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/VectorTest.java index b21b618ddb..5a92ff9bf1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/VectorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/VectorTest.java @@ -5,6 +5,14 @@ package com.microsoft.sqlserver.jdbc.datatypes; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ParameterMetaData; @@ -13,6 +21,7 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; @@ -35,14 +44,6 @@ import microsoft.sql.Vector; import microsoft.sql.Vector.VectorDimensionType; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - @RunWith(JUnitPlatform.class) @DisplayName("Test Vector Data Type") @Tag(Constants.vectorTest) @@ -52,6 +53,9 @@ public class VectorTest extends AbstractTest { private static final String tableNameWithMultipleVectorColumn = RandomUtil.getIdentifier("VECTOR_Test_MultipleColumn"); private static final String maxVectorDataTableName = RandomUtil.getIdentifier("Max_Vector_Test"); private static final String procedureName = RandomUtil.getIdentifier("VECTOR_Test_Proc"); + private static final String functionName = RandomUtil.getIdentifier("VECTOR_Test_Func"); + private static final String functionTvpName = RandomUtil.getIdentifier("VECTOR_Test_TVP_Func"); + private static final String vectorUdf = RandomUtil.getIdentifier("VectorUdf"); private static final String TABLE_NAME = RandomUtil.getIdentifier("VECTOR_TVP_Test"); private static final String TVP_NAME = RandomUtil.getIdentifier("VECTOR_TVP_Test_Type"); private static final String TVP = RandomUtil.getIdentifier("VECTOR_TVP_UDF_Test_Type"); @@ -82,6 +86,8 @@ private static void cleanupTest() throws SQLException { TestUtils.dropTypeIfExists(TVP_NAME, stmt); TestUtils.dropTableIfExists(TABLE_NAME, stmt); TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropFunctionIfExists(functionName, stmt); + TestUtils.dropFunctionIfExists(functionTvpName, stmt); } } @@ -541,53 +547,54 @@ void testVectorDataWithIncorrectDimensionCount() throws SQLException { @Test void testValidateVectorWhenVectorFEIsDisabled() throws SQLException { // Setup: create a logs table with VECTOR and VARCHAR columns - String logsTable = AbstractSQLGenerator.escapeIdentifier("logs"); + String logsTable = TestUtils.escapeSingleQuotes( + AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("vectorLogsFeiDisabled"))); try (Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(logsTable, stmt); stmt.executeUpdate("CREATE TABLE " + logsTable + " (v VECTOR(3))"); - } - // Insert a row - Object[] vectorData = new Float[] { 1.23f, 4.56f, 7.89f }; - Vector vector = new Vector(3, VectorDimensionType.FLOAT32, vectorData); - String insertSql = "INSERT INTO " + logsTable + " (v) VALUES (?)"; - try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) { - pstmt.setObject(1, vector, microsoft.sql.Types.VECTOR); - pstmt.executeUpdate(); - } + // Insert a row + Object[] vectorData = new Float[] { 1.23f, 4.56f, 7.89f }; + Vector vector = new Vector(3, VectorDimensionType.FLOAT32, vectorData); + String insertSql = "INSERT INTO " + logsTable + " (v) VALUES (?)"; + try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) { + pstmt.setObject(1, vector, microsoft.sql.Types.VECTOR); + pstmt.executeUpdate(); + } - // Use a new connection with disableVectorV1=true - try (SQLServerConnection conn = getConnectionWithVectorFlag("off"); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + logsTable)) { - - ResultSetMetaData meta = rs.getMetaData(); - int columnCount = meta.getColumnCount(); - - assertTrue(rs.next(), "No result found in logs table."); - - for (int i = 1; i <= columnCount; i++) { - int columnType = meta.getColumnType(i); - - Object value = null; - switch (columnType) { - case java.sql.Types.VARCHAR: // It will be returned as a string - value = rs.getString(i); - assertEquals("[1.2300000e+000,4.5599999e+000,7.8899999e+000]", value, - "VARCHAR column value mismatch."); - break; - case microsoft.sql.Types.VECTOR: - value = rs.getObject(i, Vector.class); - assertNotNull(value, "Vector column is null."); - assertArrayEquals(vectorData, ((Vector) value).getData(), "Vector data mismatch."); - assertEquals(3, ((Vector) value).getDimensionCount(), "Dimension count mismatch."); - assertEquals(VectorDimensionType.FLOAT32, ((Vector) value).getVectorDimensionType(), - "Dimension type mismatch."); - String expectedToString = "VECTOR(FLOAT32, 3) : [1.23, 4.56, 7.89]"; - assertEquals(expectedToString, ((Vector) value).toString(), "Vector toString output mismatch."); - break; - default: - throw new SQLException("Unexpected column type: " + columnType); + // Use a new connection with disableVectorV1=true + try (SQLServerConnection conn = getConnectionWithVectorFlag("off"); + Statement stmt2 = conn.createStatement(); + ResultSet rs = stmt2.executeQuery("SELECT * FROM " + logsTable)) { + + ResultSetMetaData meta = rs.getMetaData(); + int columnCount = meta.getColumnCount(); + + assertTrue(rs.next(), "No result found in logs table."); + + for (int i = 1; i <= columnCount; i++) { + int columnType = meta.getColumnType(i); + + Object value = null; + switch (columnType) { + case java.sql.Types.VARCHAR: // It will be returned as a string + value = rs.getString(i); + assertEquals("[1.2300000e+000,4.5599999e+000,7.8899999e+000]", value, + "VARCHAR column value mismatch."); + break; + case microsoft.sql.Types.VECTOR: + value = rs.getObject(i, Vector.class); + assertNotNull(value, "Vector column is null."); + assertArrayEquals(vectorData, ((Vector) value).getData(), "Vector data mismatch."); + assertEquals(3, ((Vector) value).getDimensionCount(), "Dimension count mismatch."); + assertEquals(VectorDimensionType.FLOAT32, ((Vector) value).getVectorDimensionType(), + "Dimension type mismatch."); + String expectedToString = "VECTOR(FLOAT32, 3) : [1.23, 4.56, 7.89]"; + assertEquals(expectedToString, ((Vector) value).toString(), "Vector toString output mismatch."); + break; + default: + throw new SQLException("Unexpected column type: " + columnType); + } } } } finally { @@ -606,53 +613,54 @@ void testValidateVectorWhenVectorFEIsDisabled() throws SQLException { @Test void testValidateVectorWhenVectorFEIsEnabled() throws SQLException { // Setup: create a logs table with VECTOR and VARCHAR columns - String logsTable = AbstractSQLGenerator.escapeIdentifier("logs"); + String logsTable = TestUtils.escapeSingleQuotes( + AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("vectorLogsFeiEnabled"))); try (Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(logsTable, stmt); stmt.executeUpdate("CREATE TABLE " + logsTable + " (v VECTOR(3))"); - } - // Insert a row - Object[] vectorData = new Float[] { 1.23f, 4.56f, 7.89f }; - Vector vector = new Vector(3, VectorDimensionType.FLOAT32, vectorData); - String insertSql = "INSERT INTO " + logsTable + " (v) VALUES (?)"; - try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) { - pstmt.setObject(1, vector, microsoft.sql.Types.VECTOR); - pstmt.executeUpdate(); - } + // Insert a row + Object[] vectorData = new Float[] { 1.23f, 4.56f, 7.89f }; + Vector vector = new Vector(3, VectorDimensionType.FLOAT32, vectorData); + String insertSql = "INSERT INTO " + logsTable + " (v) VALUES (?)"; + try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) { + pstmt.setObject(1, vector, microsoft.sql.Types.VECTOR); + pstmt.executeUpdate(); + } + + // Use a new connection with disableVectorV1=false + try (SQLServerConnection conn = getConnectionWithVectorFlag("v1"); + Statement stmt2 = conn.createStatement(); + ResultSet rs = stmt2.executeQuery("SELECT * FROM " + logsTable)) { + + ResultSetMetaData meta = rs.getMetaData(); + int columnCount = meta.getColumnCount(); - // Use a new connection with disableVectorV1=false - try (SQLServerConnection conn = getConnectionWithVectorFlag("v1"); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + logsTable)) { - - ResultSetMetaData meta = rs.getMetaData(); - int columnCount = meta.getColumnCount(); - - assertTrue(rs.next(), "No result found in logs table."); - - for (int i = 1; i <= columnCount; i++) { - int columnType = meta.getColumnType(i); - - Object value = null; - switch (columnType) { - case java.sql.Types.VARCHAR: - value = rs.getString(i); - assertEquals("[1.2300000e+000,4.5599999e+000,7.8899999e+000]", value, - "VARCHAR column value mismatch."); - break; - case microsoft.sql.Types.VECTOR: // It will be returned as a vector - value = rs.getObject(i, Vector.class); - assertNotNull(value, "Vector column is null."); - assertArrayEquals(vectorData, ((Vector) value).getData(), "Vector data mismatch."); - assertEquals(3, ((Vector) value).getDimensionCount(), "Dimension count mismatch."); - assertEquals(VectorDimensionType.FLOAT32, ((Vector) value).getVectorDimensionType(), - "Dimension type mismatch."); - String expectedToString = "VECTOR(FLOAT32, 3) : [1.23, 4.56, 7.89]"; - assertEquals(expectedToString, ((Vector) value).toString(), "Vector toString output mismatch."); - break; - default: - throw new SQLException("Unexpected column type: " + columnType); + assertTrue(rs.next(), "No result found in logs table."); + + for (int i = 1; i <= columnCount; i++) { + int columnType = meta.getColumnType(i); + + Object value = null; + switch (columnType) { + case java.sql.Types.VARCHAR: + value = rs.getString(i); + assertEquals("[1.2300000e+000,4.5599999e+000,7.8899999e+000]", value, + "VARCHAR column value mismatch."); + break; + case microsoft.sql.Types.VECTOR: // It will be returned as a vector + value = rs.getObject(i, Vector.class); + assertNotNull(value, "Vector column is null."); + assertArrayEquals(vectorData, ((Vector) value).getData(), "Vector data mismatch."); + assertEquals(3, ((Vector) value).getDimensionCount(), "Dimension count mismatch."); + assertEquals(VectorDimensionType.FLOAT32, ((Vector) value).getVectorDimensionType(), + "Dimension type mismatch."); + String expectedToString = "VECTOR(FLOAT32, 3) : [1.23, 4.56, 7.89]"; + assertEquals(expectedToString, ((Vector) value).toString(), "Vector toString output mismatch."); + break; + default: + throw new SQLException("Unexpected column type: " + columnType); + } } } } finally { @@ -669,41 +677,42 @@ void testValidateVectorWhenVectorFEIsEnabled() throws SQLException { @Test void testInvalidVectorTypeSupportConnectionProperty() throws SQLException { // Setup: create a logs table with VECTOR and VARCHAR columns - String logsTable = AbstractSQLGenerator.escapeIdentifier("logs"); + String logsTable = TestUtils + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("vectorLogs"))); try (Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(logsTable, stmt); stmt.executeUpdate("CREATE TABLE " + logsTable + " (v VECTOR(3))"); - } - - // Insert a row - Object[] vectorData = new Float[] { 1.23f, 4.56f, 7.89f }; - Vector vector = new Vector(3, VectorDimensionType.FLOAT32, vectorData); - String insertSql = "INSERT INTO " + logsTable + " (v) VALUES (?)"; - try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) { - pstmt.setObject(1, vector, microsoft.sql.Types.VECTOR); - pstmt.executeUpdate(); - } - // Try to open a connection with an invalid vectorTypeSupport value and check - // for failure - boolean exceptionThrown = false; - try { - SQLServerConnection conn = getConnectionWithVectorFlag("1"); - // If no exception, close the connection and fail the test - conn.close(); - fail("Expected IllegalArgumentException for invalid vectorTypeSupport value, but none was thrown."); - } catch (IllegalArgumentException e) { - exceptionThrown = true; - assertTrue( - e.getMessage().contains("Incorrect connection string property for vectorTypeSupport: 1"), - "Unexpected exception message: " + e.getMessage()); - } + // Insert a row + Object[] vectorData = new Float[] { 1.23f, 4.56f, 7.89f }; + Vector vector = new Vector(3, VectorDimensionType.FLOAT32, vectorData); + String insertSql = "INSERT INTO " + logsTable + " (v) VALUES (?)"; + try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) { + pstmt.setObject(1, vector, microsoft.sql.Types.VECTOR); + pstmt.executeUpdate(); + } - assertTrue(exceptionThrown, "Expected IllegalArgumentException was not thrown."); + // Try to open a connection with an invalid vectorTypeSupport value and check + // for failure + boolean exceptionThrown = false; + try { + SQLServerConnection conn = getConnectionWithVectorFlag("1"); + // If no exception, close the connection and fail the test + conn.close(); + fail("Expected IllegalArgumentException for invalid vectorTypeSupport value, but none was thrown."); + } catch (IllegalArgumentException e) { + exceptionThrown = true; + assertTrue( + e.getMessage().contains("Incorrect connection string property for vectorTypeSupport: 1"), + "Unexpected exception message: " + e.getMessage()); + } - // Cleanup - try (Statement stmt = connection.createStatement()) { - TestUtils.dropTableIfExists(logsTable, stmt); + assertTrue(exceptionThrown, "Expected IllegalArgumentException was not thrown."); + } finally { + // Cleanup + try (Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(logsTable, stmt); + } } } @@ -1006,8 +1015,8 @@ private static void createTVPReturnProcedure(String procName, String tvpTypeName */ @Test public void testStoredProcedureReturnsTVPWithVector() throws SQLException { - String tvpTypeName = AbstractSQLGenerator.escapeIdentifier("VectorTVPType"); - String procName = AbstractSQLGenerator.escapeIdentifier("sp_ReturnVectorTVP"); + String tvpTypeName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("VectorTVPType")); + String procName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("sp_ReturnVectorTVP")); // Create TVP type try (Statement stmt = connection.createStatement()) { @@ -1057,7 +1066,7 @@ public void testStoredProcedureReturnsTVPWithVector() throws SQLException { private static void createVectorUdf() throws SQLException { try (Statement stmt = connection.createStatement()) { String sql = - "CREATE OR ALTER FUNCTION " + AbstractSQLGenerator.escapeIdentifier("EchoVectorUdf") + "\n" + + "CREATE OR ALTER FUNCTION " + AbstractSQLGenerator.escapeIdentifier(functionName) + "\n" + "(@v VECTOR(3))\n" + "RETURNS VECTOR(3)\n" + "AS\n" + @@ -1085,7 +1094,7 @@ public void testVectorUdf() throws SQLException { pstmt.executeUpdate(); } - String query = "SELECT dbo." + AbstractSQLGenerator.escapeIdentifier("EchoVectorUdf") + "((SELECT TOP 1 v FROM #vec_input));"; + String query = "SELECT dbo." + AbstractSQLGenerator.escapeIdentifier(functionName) + "((SELECT TOP 1 v FROM #vec_input));"; try (PreparedStatement selectStmt = connection.prepareStatement(query); ResultSet rs = selectStmt.executeQuery()) { assertTrue(rs.next(), "Result set is empty"); @@ -1115,7 +1124,7 @@ public void testVectorUdfReturnsTVP() throws SQLException { tvp.addRow(v1); tvp.addRow(v2); - String query = "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier("VectorUdf") + "(?)"; + String query = "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(vectorUdf) + "(?)"; try (SQLServerPreparedStatement selectStmt = (SQLServerPreparedStatement) connection.prepareStatement(query)) { selectStmt.setStructured(1, TVP, tvp); try (ResultSet rs = selectStmt.executeQuery()) { @@ -1133,7 +1142,7 @@ public void testVectorUdfReturnsTVP() throws SQLException { assertEquals(2, rowCount, "Row count mismatch."); } finally { try (Statement stmt = connection.createStatement()) { - TestUtils.dropFunctionIfExists(AbstractSQLGenerator.escapeIdentifier("VectorUdf"), stmt); + TestUtils.dropFunctionIfExists(AbstractSQLGenerator.escapeIdentifier(vectorUdf), stmt); } } } @@ -1141,7 +1150,7 @@ public void testVectorUdfReturnsTVP() throws SQLException { private static void createTVPReturnUdf() throws SQLException { try (Statement stmt = connection.createStatement()) { - String sql = "CREATE OR ALTER FUNCTION " + AbstractSQLGenerator.escapeIdentifier("VectorUdf") + + String sql = "CREATE OR ALTER FUNCTION " + AbstractSQLGenerator.escapeIdentifier(vectorUdf) + "(@tvpInput " + AbstractSQLGenerator.escapeIdentifier(TVP) + " READONLY)\n" + "RETURNS TABLE\n" + "AS\n" + @@ -1157,8 +1166,8 @@ private static void createTVPReturnUdf() throws SQLException { */ @Test public void testSelectIntoForVector() throws SQLException { - String sourceTable = AbstractSQLGenerator.escapeIdentifier("srcTableVector"); - String destinationTable = AbstractSQLGenerator.escapeIdentifier("desTable"); + String sourceTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("srcTableVector")); + String destinationTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("desTable")); try (Statement stmt = connection.createStatement()) { // Create the source table @@ -1316,7 +1325,8 @@ public void testVectorInsertionInLocalTempTable() throws SQLException { public void testVectorNormalizeUdf() throws SQLException { String vectorsTable = TestUtils .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("Vectors"))); - String udfName = "dbo.udf2"; + String udfName = TestUtils + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(functionTvpName)); try (Statement stmt = connection.createStatement()) { // Create the UDF @@ -1374,7 +1384,8 @@ public void testVectorNormalizeUdf() throws SQLException { public void testVectorNormalizeScalarFunction() throws SQLException { String vectorsTable = TestUtils .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("Vectors"))); - String udfName = "dbo.svf"; + String udfName = TestUtils + .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("svf"))); try (Statement stmt = connection.createStatement()) { // Drop table and UDF if they already exist @@ -1440,84 +1451,84 @@ public void testVectorNormalizeScalarFunction() throws SQLException { */ @Test public void testTransactionRollbackForVector() throws SQLException { - String transactionTable = AbstractSQLGenerator.escapeIdentifier("transactionTable"); + String transactionTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("transactionTable")); // Create the table - try (Statement stmt = connection.createStatement()) { - TestUtils.dropTableIfExists(transactionTable, stmt); + try (Statement outerStmt = connection.createStatement()) { + TestUtils.dropTableIfExists(transactionTable, outerStmt); String createTableSQL = "CREATE TABLE " + transactionTable + " (id INT PRIMARY KEY, v VECTOR(3))"; - stmt.executeUpdate(createTableSQL); - } - - // Insert initial data - Object[] initialData = new Float[] { 1.0f, 2.0f, 3.0f }; - Vector initialVector = new Vector(3, VectorDimensionType.FLOAT32, initialData); + outerStmt.executeUpdate(createTableSQL); - try (PreparedStatement pstmt = connection.prepareStatement( - "INSERT INTO " + transactionTable + " (id, v) VALUES (?, ?)")) { - pstmt.setInt(1, 1); - pstmt.setObject(2, initialVector, microsoft.sql.Types.VECTOR); - pstmt.executeUpdate(); - } - - // Start a transaction - connection.setAutoCommit(false); - try { - // Insert new data - Object[] newData = new Float[] { 4.0f, 5.0f, 6.0f }; - Vector newVector = new Vector(3, VectorDimensionType.FLOAT32, newData); + // Insert initial data + Object[] initialData = new Float[] { 1.0f, 2.0f, 3.0f }; + Vector initialVector = new Vector(3, VectorDimensionType.FLOAT32, initialData); try (PreparedStatement pstmt = connection.prepareStatement( "INSERT INTO " + transactionTable + " (id, v) VALUES (?, ?)")) { - pstmt.setInt(1, 2); - pstmt.setObject(2, newVector, microsoft.sql.Types.VECTOR); + pstmt.setInt(1, 1); + pstmt.setObject(2, initialVector, microsoft.sql.Types.VECTOR); pstmt.executeUpdate(); } - // Update existing data - Object[] updatedData = new Float[] { 7.0f, 8.0f, 9.0f }; - Vector updatedVector = new Vector(3, VectorDimensionType.FLOAT32, updatedData); + // Start a transaction + connection.setAutoCommit(false); + try { + // Insert new data + Object[] newData = new Float[] { 4.0f, 5.0f, 6.0f }; + Vector newVector = new Vector(3, VectorDimensionType.FLOAT32, newData); + + try (PreparedStatement pstmt = connection.prepareStatement( + "INSERT INTO " + transactionTable + " (id, v) VALUES (?, ?)")) { + pstmt.setInt(1, 2); + pstmt.setObject(2, newVector, microsoft.sql.Types.VECTOR); + pstmt.executeUpdate(); + } - try (PreparedStatement pstmt = connection.prepareStatement( - "UPDATE " + transactionTable + " SET v = ? WHERE id = ?")) { - pstmt.setObject(1, updatedVector, microsoft.sql.Types.VECTOR); - pstmt.setInt(2, 1); - pstmt.executeUpdate(); - } + // Update existing data + Object[] updatedData = new Float[] { 7.0f, 8.0f, 9.0f }; + Vector updatedVector = new Vector(3, VectorDimensionType.FLOAT32, updatedData); - // Delete a row - try (PreparedStatement pstmt = connection.prepareStatement( - "DELETE FROM " + transactionTable + " WHERE id = ?")) { - pstmt.setInt(1, 2); - pstmt.executeUpdate(); - } + try (PreparedStatement pstmt = connection.prepareStatement( + "UPDATE " + transactionTable + " SET v = ? WHERE id = ?")) { + pstmt.setObject(1, updatedVector, microsoft.sql.Types.VECTOR); + pstmt.setInt(2, 1); + pstmt.executeUpdate(); + } - // Simulate a failure - throw new RuntimeException("Simulated failure to trigger rollback"); + // Delete a row + try (PreparedStatement pstmt = connection.prepareStatement( + "DELETE FROM " + transactionTable + " WHERE id = ?")) { + pstmt.setInt(1, 2); + pstmt.executeUpdate(); + } - } catch (RuntimeException e) { - // Rollback the transaction - connection.rollback(); - System.out.println("Transaction rolled back due to: " + e.getMessage()); - } finally { - // Restore auto-commit mode - connection.setAutoCommit(true); - } + // Simulate a failure + throw new RuntimeException("Simulated failure to trigger rollback"); - // Validate that the data is restored to its original state - String validateSql = "SELECT id, v FROM " + transactionTable + " ORDER BY id"; - try (Statement stmt = connection.createStatement(); - ResultSet rs = stmt.executeQuery(validateSql)) { + } catch (RuntimeException e) { + // Rollback the transaction + connection.rollback(); + System.out.println("Transaction rolled back due to: " + e.getMessage()); + } finally { + // Restore auto-commit mode + connection.setAutoCommit(true); + } + + // Validate that the data is restored to its original state + String validateSql = "SELECT id, v FROM " + transactionTable + " ORDER BY id"; + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery(validateSql)) { - assertTrue(rs.next(), "No data found in the table after rollback."); - int id = rs.getInt("id"); - Vector resultVector = rs.getObject("v", Vector.class); + assertTrue(rs.next(), "No data found in the table after rollback."); + int id = rs.getInt("id"); + Vector resultVector = rs.getObject("v", Vector.class); - assertEquals(1, id, "ID mismatch after rollback."); - assertNotNull(resultVector, "Vector is null after rollback."); - assertArrayEquals(initialData, resultVector.getData(), "Vector data mismatch after rollback."); + assertEquals(1, id, "ID mismatch after rollback."); + assertNotNull(resultVector, "Vector is null after rollback."); + assertArrayEquals(initialData, resultVector.getData(), "Vector data mismatch after rollback."); - assertFalse(rs.next(), "Unexpected additional rows found after rollback."); + assertFalse(rs.next(), "Unexpected additional rows found after rollback."); + } } finally { // Cleanup: Drop the table try (Statement stmt = connection.createStatement()) { @@ -1534,8 +1545,8 @@ public void testTransactionRollbackForVector() throws SQLException { */ @Test public void testViewWithVectorDataType() throws SQLException { - String tableName = AbstractSQLGenerator.escapeIdentifier("VectorTable"); - String viewName = AbstractSQLGenerator.escapeIdentifier("VectorView"); + String tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("VectorTable")); + String viewName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("VectorView")); try (Statement stmt = connection.createStatement()) { // Create the table 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 cc8d2d4e58..d6d1df792c 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java @@ -32,8 +32,8 @@ import java.util.UUID; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; @@ -1531,6 +1531,7 @@ public static void terminateVariation() throws SQLException { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(schemaTableName), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameBulkString), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameBulkComputedCols), 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 53b5d89ceb..842f0d5a69 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java @@ -31,11 +31,6 @@ import java.util.TimeZone; import java.util.UUID; -import com.microsoft.sqlserver.jdbc.SQLServerConnection; -import com.microsoft.sqlserver.jdbc.SQLServerException; -import com.microsoft.sqlserver.jdbc.SQLServerResultSet; -import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.PrepUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -46,10 +41,15 @@ import com.microsoft.sqlserver.jdbc.ISQLServerResultSet; import com.microsoft.sqlserver.jdbc.RandomUtil; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; +import com.microsoft.sqlserver.jdbc.SQLServerException; +import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +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.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) public class ResultSetTest extends AbstractTest { @@ -716,8 +716,8 @@ public void testResultSetClientCursorInitializerSqlErrorState() { @Test @Tag(Constants.JSONTest) public void testCastOnJSON() throws SQLException { - String dstTable = TestUtils - .escapeSingleQuotes(AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTable"))); + String dstTable = TestUtils.escapeSingleQuotes( + AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("dstTableCastJson"))); String jsonData = "{\"key\":\"123\"}"; 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 51a93fdfa2..0b779002e5 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 @@ -8,9 +8,9 @@ import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; import java.lang.reflect.Field; import java.sql.BatchUpdateException; @@ -528,43 +528,49 @@ public void testBatchSpPrepare() throws Exception { @Test public void testBatchStatementCancellation() throws Exception { + String testTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("test_table")); try (Connection connection = PrepUtil.getConnection(connectionString)) { connection.setAutoCommit(false); - try (PreparedStatement statement = connection - .prepareStatement("if object_id('test_table') is not null drop table test_table")) { - statement.execute(); + try (Statement statement = connection.createStatement()) { + TestUtils.dropTableIfExists(testTable, statement); } connection.commit(); - try (PreparedStatement statement = connection - .prepareStatement("create table test_table (column_name bit)")) { - statement.execute(); + try (Statement statement = connection.createStatement()) { + statement.execute("create table " + testTable + " (column_name bit)"); } connection.commit(); - for (long delayInMilliseconds : new long[] {1, 2, 4, 8, 16, 32, 64, 128}) { - for (int numberOfCommands : new int[] {1, 2, 4, 8, 16, 32, 64}) { - int parameterCount = 512; - - try (PreparedStatement statement = connection.prepareStatement( - "insert into test_table values (?)" + repeat(",(?)", parameterCount - 1))) { - - for (int i = 0; i < numberOfCommands; i++) { - for (int j = 0; j < parameterCount; j++) { - statement.setBoolean(j + 1, true); + try { + for (long delayInMilliseconds : new long[] {1, 2, 4, 8, 16, 32, 64, 128}) { + for (int numberOfCommands : new int[] {1, 2, 4, 8, 16, 32, 64}) { + int parameterCount = 512; + + try (PreparedStatement statement = connection.prepareStatement( + "insert into " + testTable + " values (?)" + repeat(",(?)", parameterCount - 1))) { + + for (int i = 0; i < numberOfCommands; i++) { + for (int j = 0; j < parameterCount; j++) { + statement.setBoolean(j + 1, true); + } + statement.addBatch(); } - statement.addBatch(); - } - Thread cancelThread = cancelAsync(statement, delayInMilliseconds); - try { - statement.executeBatch(); - } catch (SQLException e) { - assertEquals(TestResource.getResource("R_queryCanceled"), e.getMessage()); + Thread cancelThread = cancelAsync(statement, delayInMilliseconds); + try { + statement.executeBatch(); + } catch (SQLException e) { + assertEquals(TestResource.getResource("R_queryCanceled"), e.getMessage()); + } + cancelThread.join(); } - cancelThread.join(); + connection.commit(); } + } + } finally { + try (Statement statement = connection.createStatement()) { + TestUtils.dropTableIfExists(testTable, statement); connection.commit(); } } @@ -955,6 +961,7 @@ private static void dropTable() throws SQLException { @AfterAll public static void terminateVariation() throws Exception { + dropProcedure(); dropTable(); } } 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 ab8d4ce228..5176728ce9 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 @@ -96,8 +96,9 @@ public void datatypesTest() throws SQLException { } try (ResultSet rs = callableStatement.executeQuery()) {} + } finally { + terminateVariation(statement); } - terminateVariation(statement); } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java b/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java index acf08434b9..4adbe62c17 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java @@ -73,4 +73,12 @@ public static String escapeIdentifier(String value) { return OPEN_ESCAPE_IDENTIFIER + value + CLOSE_ESCAPE_IDENTIFIER; } + public static String unEscapeIdentifier(String value) { + if (value != null && value.startsWith(OPEN_ESCAPE_IDENTIFIER) && value.endsWith(CLOSE_ESCAPE_IDENTIFIER)) { + value = value.substring(1, value.length() - 1); + } + + return value; + } + }