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 a811dc505..c84c3dd72 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -1,6 +1,6 @@ /* * 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. + * available under the terms of the MIT License. See the LICENSE file in the project root for more AEInformation. */ package com.microsoft.sqlserver.jdbc.AlwaysEncrypted; @@ -20,6 +20,7 @@ import java.sql.Timestamp; import java.util.LinkedList; import java.util.Properties; +import java.util.UUID; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -28,6 +29,7 @@ import org.opentest4j.TestAbortedException; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerConnection; @@ -36,6 +38,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatementColumnEncryptionSetting; 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; @@ -57,23 +60,25 @@ public class AESetup extends AbstractTest { static final String cmkName = "JDBC_CMK"; static final String cekName = "JDBC_CEK"; static final String secretstrJks = "password"; - static final String charTable = "JDBCEncryptedCharTable"; - static final String binaryTable = "JDBCEncryptedBinaryTable"; - static final String dateTable = "JDBCEncryptedDateTable"; - static final String numericTable = "JDBCEncryptedNumericTable"; - static final String scaleDateTable = "JDBCEncryptedScaleDateTable"; - static final String uid = "171fbe25-4331-4765-a838-b2e3eea3e7ea"; + static String charTable = RandomUtil.getIdentifier("JDBCEncryptedChar"); + static String binaryTable = RandomUtil.getIdentifier("JDBCEncryptedBinary"); + static String dateTable = RandomUtil.getIdentifier("JDBCEncryptedDate"); + static String numericTable = RandomUtil.getIdentifier("JDBCEncryptedNumeric"); + static String scaleDateTable = RandomUtil.getIdentifier("JDBCEncryptedScaleDate"); + + static final String uid = UUID.randomUUID().toString(); static String filePath = null; static String thumbprint = null; - static SQLServerConnection con = null; - static SQLServerStatement stmt = null; static String keyPath = null; static String javaKeyAliases = null; static String OS = System.getProperty("os.name").toLowerCase(); static SQLServerColumnEncryptionKeyStoreProvider storeProvider = null; static SQLServerStatementColumnEncryptionSetting stmtColEncSetting = null; + static String AETestConnectionString; + + static Properties AEInfo; /** * Create connection, statement and generate path of resource file @@ -86,10 +91,9 @@ public static void setUpConnection() throws TestAbortedException, Exception { try (DBConnection con = new DBConnection(connectionString)) { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - - String AETestConnectionString = connectionString + ";sendTimeAsDateTime=false"; + + AETestConnectionString = connectionString + ";sendTimeAsDateTime=false"; readFromFile(javaKeyStoreInputFile, "Alias name"); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropCEK(stmt); @@ -100,14 +104,12 @@ public static void setUpConnection() throws TestAbortedException, Exception { storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, secretstrJks.toCharArray()); stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.Enabled; - Properties info = new Properties(); - info.setProperty("ColumnEncryptionSetting", "Enabled"); - info.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); - info.setProperty("keyStoreLocation", keyPath); - info.setProperty("keyStoreSecret", secretstrJks); + AEInfo = new Properties(); + AEInfo.setProperty("ColumnEncryptionSetting", "Enabled"); + AEInfo.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); + AEInfo.setProperty("keyStoreLocation", keyPath); + AEInfo.setProperty("keyStoreSecret", secretstrJks); - con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, info); - stmt = (SQLServerStatement) con.createStatement(); createCMK(keyStoreName, javaKeyAliases); createCEK(storeProvider); } @@ -119,14 +121,17 @@ public static void setUpConnection() throws TestAbortedException, Exception { * @throws SQLException */ @AfterAll - public static void dropAll() throws Exception { + public static void dropAll() throws Exception { try (DBConnection con = new DBConnection(connectionString)) { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - dropTables(stmt); - dropCEK(stmt); - dropCMK(stmt); - TestUtils.close(null, stmt, con); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + dropCEK(stmt); + dropCMK(stmt); + } } /** @@ -165,7 +170,8 @@ private static void readFromFile(String inputFile, String lookupValue) throws IO * @throws SQLException */ protected static void createBinaryTable() throws SQLException { - String sql = "create table " + binaryTable + " (" + "PlainBinary binary(20) null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " (" + + "PlainBinary binary(20) null," + "RandomizedBinary binary(20) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicBinary binary(20) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -197,7 +203,8 @@ protected static void createBinaryTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -211,7 +218,8 @@ protected static void createBinaryTable() throws SQLException { * @throws SQLException */ protected static void createCharTable() throws SQLException { - String sql = "create table " + charTable + " (" + "PlainChar char(20) null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (" + + "PlainChar char(20) null," + "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -267,7 +275,8 @@ protected static void createCharTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -281,7 +290,7 @@ protected static void createCharTable() throws SQLException { * @throws SQLException */ protected void createDateTable() throws SQLException { - String sql = "create table " + dateTable + " (" + "PlainDate date null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + "PlainDate date null," + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicDate date ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -319,7 +328,8 @@ protected void createDateTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -333,7 +343,7 @@ protected void createDateTable() throws SQLException { * @throws SQLException */ protected void createDatePrecisionTable(int scale) throws SQLException { - String sql = "create table " + dateTable + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" // 1 + "PlainDatetime2 datetime2(" + scale + ") null," + "RandomizedDatetime2 datetime2(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -379,7 +389,8 @@ protected void createDatePrecisionTable(int scale) throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -393,7 +404,7 @@ protected void createDatePrecisionTable(int scale) throws SQLException { * @throws SQLException */ protected static void createDateScaleTable() throws SQLException { - String sql = "create table " + scaleDateTable + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + " (" + "PlainDatetime2 datetime2(2) null," + "RandomizedDatetime2 datetime2(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -415,7 +426,8 @@ protected static void createDateScaleTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -429,7 +441,7 @@ protected static void createDateScaleTable() throws SQLException { * @throws SQLException */ protected static void createNumericTable() throws SQLException { - String sql = "create table " + numericTable + " (" + "PlainBit bit null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainBit bit null," + "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -527,7 +539,8 @@ protected static void createNumericTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -541,8 +554,8 @@ protected static void createNumericTable() throws SQLException { * @throws SQLException */ protected void createNumericPrecisionTable(int floatPrecision, int precision, int scale) throws SQLException { - String sql = "create table " + numericTable + " (" + "PlainFloat float(" + floatPrecision + ") null," - + "RandomizedFloat float(" + floatPrecision + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainFloat float(" + + floatPrecision + ") null," + "RandomizedFloat float(" + floatPrecision + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicFloat float(" + floatPrecision + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -564,7 +577,8 @@ protected void createNumericPrecisionTable(int floatPrecision, int precision, in + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -687,7 +701,7 @@ protected static LinkedList createTemporalTypes(boolean nullable) { */ private static void createCMK(String keyStoreName, String keyPath) throws SQLException { try (SQLServerConnection con = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); 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 = '" @@ -705,7 +719,7 @@ private static void createCMK(String keyStoreName, String keyPath) throws SQLExc */ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storeProvider) throws SQLException { try (SQLServerConnection con = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String letters = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] valuesDefault = letters.getBytes(); @@ -724,10 +738,10 @@ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storePro * @throws SQLException */ protected static void dropTables(SQLServerStatement statement) throws SQLException { - TestUtils.dropTableIfExists(numericTable, statement); - TestUtils.dropTableIfExists(charTable, statement); - TestUtils.dropTableIfExists(binaryTable, statement); - TestUtils.dropTableIfExists(dateTable, statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(binaryTable), statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateTable), statement); } /** @@ -737,11 +751,11 @@ protected static void dropTables(SQLServerStatement statement) throws SQLExcepti * @throws SQLException */ protected static void populateBinaryNormalCase(LinkedList byteValues) throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; try (SQLServerConnection con = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -801,10 +815,11 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th * @throws SQLException */ protected static void populateBinarySetObject(LinkedList byteValues) throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; - - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // binary(20) @@ -863,11 +878,13 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr * @throws SQLException */ protected static void populateBinarySetObjectWithJDBCType(LinkedList byteValues) throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // binary(20) for (int i = 1; i <= 3; i++) { @@ -924,11 +941,13 @@ protected static void populateBinarySetObjectWithJDBCType(LinkedList byt * @throws SQLException */ protected static void populateBinaryNullCase() throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // binary for (int i = 1; i <= 3; i++) { @@ -961,11 +980,13 @@ protected static void populateBinaryNullCase() throws SQLException { * @throws SQLException */ protected static void populateCharNormalCase(String[] charValues) throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // char for (int i = 1; i <= 3; i++) { @@ -1027,10 +1048,12 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce * @throws SQLException */ protected static void populateCharSetObject(String[] charValues) throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1089,10 +1112,12 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep * @throws SQLException */ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1150,10 +1175,12 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th * @throws SQLException */ protected static void populateCharNullCase() throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1203,10 +1230,12 @@ protected static void populateCharNullCase() throws SQLException { * @throws SQLException */ protected static void populateDateNormalCase(LinkedList dateValues) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1250,9 +1279,12 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro * @throws SQLException */ protected static void populateDateScaleNormalCase(LinkedList dateValues) throws SQLException { - String sql = "insert into " + scaleDateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // datetime2(2) @@ -1286,10 +1318,12 @@ protected static void populateDateSetObject(LinkedList dateValues, Strin skipTestForJava7(); } - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1352,10 +1386,12 @@ else if (setter.equalsIgnoreCase("setwithJDBCType")) * @throws SQLException */ protected void populateDateSetObjectNull() throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1398,10 +1434,12 @@ protected void populateDateSetObjectNull() throws SQLException { * @throws SQLException */ protected static void populateDateNullCase() throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1445,11 +1483,13 @@ protected static void populateDateNullCase() throws SQLException { * @throws SQLException */ protected static void populateNumeric(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1553,11 +1593,13 @@ protected static void populateNumeric(String[] values) throws SQLException { * @throws SQLException */ protected static void populateNumericSetObject(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1661,11 +1703,13 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept * @throws SQLException */ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1768,11 +1812,13 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr * @throws SQLException */ protected static void populateNumericSetObjectNull() throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1866,13 +1912,15 @@ protected static void populateNumericSetObjectNull() throws SQLException { * @throws SQLException */ protected static void populateNumericNullCase(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1965,13 +2013,15 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti * @throws SQLException */ protected static void populateNumericNormalCase(String[] numericValues) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -2078,7 +2128,7 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S private static void dropCEK(SQLServerStatement stmt) throws SQLException { String cekSql = " if exists (SELECT name from sys.column_encryption_keys where name='" + cekName + "')" + " begin" + " drop column encryption key " + cekName + " end"; - stmt.execute(cekSql); + stmt.execute(cekSql); } /** @@ -2099,6 +2149,9 @@ 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. + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo)) { + 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 427ef814e..f2f7eb657 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -11,6 +11,7 @@ import java.math.BigDecimal; import java.sql.Date; +import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; @@ -24,11 +25,15 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; 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.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.DBConnection; import microsoft.sql.DateTimeOffset; @@ -41,37 +46,32 @@ @RunWith(JUnitPlatform.class) public class CallableStatementTest extends AESetup { - private static String multiStatementsProcedure = "multiStatementsProcedure"; - - private static String inputProcedure = "inputProcedure"; - private static String inputProcedure2 = "inputProcedure2"; - - private static String outputProcedure = "outputProcedure"; - private static String outputProcedure2 = "outputProcedure2"; - private static String outputProcedure3 = "outputProcedure3"; - private static String outputProcedureChar = "outputProcedureChar"; - private static String outputProcedureNumeric = "outputProcedureNumeric"; - private static String outputProcedureBinary = "outputProcedureBinary"; - private static String outputProcedureDate = "outputProcedureDate"; - private static String MixedProcedureDateScale = "outputProcedureDateScale"; - private static String outputProcedureBatch = "outputProcedureBatch"; - private static String outputProcedure4 = "outputProcedure4"; - - private static String inoutProcedure = "inoutProcedure"; - - private static String mixedProcedure = "mixedProcedure"; - private static String mixedProcedure2 = "mixedProcedure2"; - private static String mixedProcedure3 = "mixedProcedure3"; - private static String mixedProcedureNumericPrcisionScale = "mixedProcedureNumericPrcisionScale"; - - private static String table1 = "StoredProcedureTable1"; - private static String table2 = "StoredProcedureTable2"; - private static String table3 = "StoredProcedureTable3"; - private static String table4 = "StoredProcedureTable4"; - private static String table5 = "StoredProcedureTable5"; - private static String table6 = "StoredProcedureTable6"; - - static final String uid = "171fbe25-4331-4765-a838-b2e3eea3e7ea"; + private static String multiStatementsProcedure = RandomUtil.getIdentifier("multiStatementsProcedure"); + private static String inputProcedure = RandomUtil.getIdentifier("inputProcedure"); + private static String inputProcedure2 = RandomUtil.getIdentifier("inputProcedure2"); + private static String outputProcedure = RandomUtil.getIdentifier("outputProcedure"); + private static String outputProcedure2 = RandomUtil.getIdentifier("outputProcedure2"); + private static String outputProcedure3 = RandomUtil.getIdentifier("outputProcedure3"); + private static String outputProcedure4 = RandomUtil.getIdentifier("outputProcedure4"); + private static String outputProcedureChar = RandomUtil.getIdentifier("outputProcedureChar"); + private static String outputProcedureNumeric = RandomUtil.getIdentifier("outputProcedureNumeric"); + private static String outputProcedureBinary = RandomUtil.getIdentifier("outputProcedureBinary"); + private static String outputProcedureDate = RandomUtil.getIdentifier("outputProcedureDate"); + private static String outputProcedureDateScale = RandomUtil.getIdentifier("outputProcedureDateScale"); + private static String outputProcedureBatch = RandomUtil.getIdentifier("outputProcedureBatch"); + private static String inoutProcedure = RandomUtil.getIdentifier("inoutProcedure"); + private static String mixedProcedure = RandomUtil.getIdentifier("mixedProcedure"); + private static String mixedProcedure2 = RandomUtil.getIdentifier("mixedProcedure2"); + private static String mixedProcedure3 = RandomUtil.getIdentifier("mixedProcedure3"); + private static String mixedProcedureNumericPrcisionScale = RandomUtil + .getIdentifier("mixedProcedureNumericPrcisionScale"); + + private static String table1 = RandomUtil.getIdentifier("StoredProcedure_table1"); + private static String table2 = RandomUtil.getIdentifier("StoredProcedure_table2"); + private static String table3 = RandomUtil.getIdentifier("StoredProcedure_table3"); + private static String table4 = RandomUtil.getIdentifier("StoredProcedure_table4"); + private static String table5 = RandomUtil.getIdentifier("StoredProcedure_table5"); + private static String table6 = RandomUtil.getIdentifier("StoredProcedure_table6"); private static String[] numericValues; private static LinkedList byteValues; @@ -90,7 +90,7 @@ public static void initCallableStatementTest() throws Exception { try (DBConnection con = new DBConnection(connectionString)) { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - + dropTables(); numericValues = createNumericValues(nullable); @@ -121,6 +121,7 @@ public static void dropAll() throws Exception { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } dropTables(); + dropProcedures(); } @Test @@ -132,51 +133,63 @@ public void testMultiInsertionSelection() throws SQLException { @Test public void testInputProcedureNumeric() throws SQLException { createInputProcedure(); - testInputProcedure("{call " + inputProcedure + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}", numericValues); + testInputProcedure( + "{call " + AbstractSQLGenerator.escapeIdentifier(inputProcedure) + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}", + numericValues); } @Test public void testInputProcedureChar() throws SQLException { createInputProcedure2(); - testInputProcedure2("{call " + inputProcedure2 + "(?,?,?,?,?,?,?,?)}"); + testInputProcedure2("{call " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2) + "(?,?,?,?,?,?,?,?)}"); } @Test public void testEncryptedOutputNumericParams() throws SQLException { createOutputProcedure(); - testOutputProcedureRandomOrder("{call " + outputProcedure + "(?,?,?,?,?,?,?)}", numericValues); - testOutputProcedureInorder("{call " + outputProcedure + "(?,?,?,?,?,?,?)}", numericValues); - testOutputProcedureReverseOrder("{call " + outputProcedure + "(?,?,?,?,?,?,?)}", numericValues); - testOutputProcedureRandomOrder("exec " + outputProcedure + " ?,?,?,?,?,?,?", numericValues); + testOutputProcedureRandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + "(?,?,?,?,?,?,?)}", numericValues); + testOutputProcedureInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + "(?,?,?,?,?,?,?)}", numericValues); + testOutputProcedureReverseOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + "(?,?,?,?,?,?,?)}", numericValues); + testOutputProcedureRandomOrder( + "exec " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + " ?,?,?,?,?,?,?", numericValues); } @Test public void testUnencryptedAndEncryptedNumericOutputParams() throws SQLException { createOutputProcedure2(); - testOutputProcedure2RandomOrder("{call " + outputProcedure2 + "(?,?,?,?,?,?,?,?,?,?)}", numericValues); - testOutputProcedure2Inorder("{call " + outputProcedure2 + "(?,?,?,?,?,?,?,?,?,?)}", numericValues); - testOutputProcedure2ReverseOrder("{call " + outputProcedure2 + "(?,?,?,?,?,?,?,?,?,?)}", numericValues); + testOutputProcedure2RandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + "(?,?,?,?,?,?,?,?,?,?)}", + numericValues); + testOutputProcedure2Inorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + "(?,?,?,?,?,?,?,?,?,?)}", + numericValues); + testOutputProcedure2ReverseOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + "(?,?,?,?,?,?,?,?,?,?)}", + numericValues); } @Test public void testEncryptedOutputParamsFromDifferentTables() throws SQLException { createOutputProcedure3(); - testOutputProcedure3RandomOrder("{call " + outputProcedure3 + "(?,?)}"); - testOutputProcedure3Inorder("{call " + outputProcedure3 + "(?,?)}"); - testOutputProcedure3ReverseOrder("{call " + outputProcedure3 + "(?,?)}"); + testOutputProcedure3RandomOrder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + "(?,?)}"); + testOutputProcedure3Inorder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + "(?,?)}"); + testOutputProcedure3ReverseOrder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + "(?,?)}"); } @Test public void testInOutProcedure() throws SQLException { createInOutProcedure(); - testInOutProcedure("{call " + inoutProcedure + "(?)}"); - testInOutProcedure("exec " + inoutProcedure + " ?"); + testInOutProcedure("{call " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure) + "(?)}"); + testInOutProcedure("exec " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure) + " ?"); } @Test public void testMixedProcedure() throws SQLException { createMixedProcedure(); - testMixedProcedure("{ ? = call " + mixedProcedure + "(?,?,?)}"); + testMixedProcedure("{ ? = call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure) + "(?,?,?)}"); } @Test @@ -184,67 +197,82 @@ public void testUnencryptedAndEncryptedIOParams() throws SQLException { // unencrypted input and output parameter // encrypted input and output parameter createMixedProcedure2(); - testMixedProcedure2RandomOrder("{call " + mixedProcedure2 + "(?,?,?,?)}"); - testMixedProcedure2Inorder("{call " + mixedProcedure2 + "(?,?,?,?)}"); + testMixedProcedure2RandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2) + "(?,?,?,?)}"); + testMixedProcedure2Inorder("{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2) + "(?,?,?,?)}"); } @Test public void testUnencryptedIOParams() throws SQLException { createMixedProcedure3(); - testMixedProcedure3RandomOrder("{call " + mixedProcedure3 + "(?,?,?,?)}"); - testMixedProcedure3Inorder("{call " + mixedProcedure3 + "(?,?,?,?)}"); - testMixedProcedure3ReverseOrder("{call " + mixedProcedure3 + "(?,?,?,?)}"); + testMixedProcedure3RandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + "(?,?,?,?)}"); + testMixedProcedure3Inorder("{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + "(?,?,?,?)}"); + testMixedProcedure3ReverseOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + "(?,?,?,?)}"); } @Test public void testVariousIOParams() throws SQLException { createMixedProcedureNumericPrcisionScale(); - testMixedProcedureNumericPrcisionScaleInorder("{call " + mixedProcedureNumericPrcisionScale + "(?,?,?,?)}"); + testMixedProcedureNumericPrcisionScaleInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale) + "(?,?,?,?)}"); testMixedProcedureNumericPrcisionScaleParameterName( - "{call " + mixedProcedureNumericPrcisionScale + "(?,?,?,?)}"); + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale) + "(?,?,?,?)}"); } @Test public void testOutputProcedureChar() throws SQLException { createOutputProcedureChar(); - testOutputProcedureCharInorder("{call " + outputProcedureChar + "(?,?,?,?,?,?,?,?,?)}"); - testOutputProcedureCharInorderObject("{call " + outputProcedureChar + "(?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureCharInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar) + "(?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureCharInorderObject( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar) + "(?,?,?,?,?,?,?,?,?)}"); } @Test public void testOutputProcedureNumeric() throws SQLException { createOutputProcedureNumeric(); - testOutputProcedureNumericInorder("{call " + outputProcedureNumeric + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); - testcoerctionsOutputProcedureNumericInorder( - "{call " + outputProcedureNumeric + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureNumericInorder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric) + + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testcoerctionsOutputProcedureNumericInorder("{call " + + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric) + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); } @Test public void testOutputProcedureBinary() throws SQLException { createOutputProcedureBinary(); - testOutputProcedureBinaryInorder("{call " + outputProcedureBinary + "(?,?,?,?,?)}"); - testOutputProcedureBinaryInorderObject("{call " + outputProcedureBinary + "(?,?,?,?,?)}"); - testOutputProcedureBinaryInorderString("{call " + outputProcedureBinary + "(?,?,?,?,?)}"); + testOutputProcedureBinaryInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + "(?,?,?,?,?)}"); + testOutputProcedureBinaryInorderObject( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + "(?,?,?,?,?)}"); + testOutputProcedureBinaryInorderString( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + "(?,?,?,?,?)}"); } @Test public void testOutputProcedureDate() throws SQLException { createOutputProcedureDate(); - testOutputProcedureDateInorder("{call " + outputProcedureDate + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); - testOutputProcedureDateInorderObject("{call " + outputProcedureDate + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureDateInorder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate) + + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureDateInorderObject("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate) + + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); } @Test public void testMixedProcedureDateScale() throws SQLException { createMixedProcedureDateScale(); - testMixedProcedureDateScaleInorder("{call " + MixedProcedureDateScale + "(?,?,?,?,?,?)}"); - testMixedProcedureDateScaleWithParameterName("{call " + MixedProcedureDateScale + "(?,?,?,?,?,?)}"); + testMixedProcedureDateScaleInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale) + "(?,?,?,?,?,?)}"); + testMixedProcedureDateScaleWithParameterName( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale) + "(?,?,?,?,?,?)}"); } @Test public void testOutputProcedureBatch() throws SQLException { createOutputProcedureBatch(); - testOutputProcedureBatchInorder("{call " + outputProcedureBatch + "(?,?,?,?)}"); + testOutputProcedureBatchInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch) + "(?,?,?,?)}"); } @Test @@ -252,32 +280,49 @@ public void testOutputProcedure4() throws SQLException { createOutputProcedure4(); } - private static void dropTables() throws SQLException { - TestUtils.dropTableIfExists(table1, stmt); - - TestUtils.dropTableIfExists(table2, stmt); - - TestUtils.dropTableIfExists(table3, stmt); - - TestUtils.dropTableIfExists(table4, stmt); - - TestUtils.dropTableIfExists(charTable, stmt); - - TestUtils.dropTableIfExists(numericTable, stmt); - - TestUtils.dropTableIfExists(binaryTable, stmt); - - TestUtils.dropTableIfExists(dateTable, stmt); - - TestUtils.dropTableIfExists(table5, stmt); - - TestUtils.dropTableIfExists(table6, stmt); + private static void dropProcedures() throws SQLException { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProcedure2), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure2), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure3), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure4), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureChar), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureDate), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inoutProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedure2), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedure3), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale), stmt); + } + } - TestUtils.dropTableIfExists(scaleDateTable, stmt); + private static void dropTables() throws SQLException { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table3), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table4), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(binaryTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table5), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table6), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(scaleDateTable), stmt); + } } private static void createTables() throws SQLException { - String sql = "create table " + table1 + " (" + "PlainChar char(20) null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table1) + " (" + "PlainChar char(20) null," + "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -289,13 +334,14 @@ private static void createTables() throws SQLException { + "DeterministicVarchar varchar(50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL" + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table2 + " (" + "PlainChar char(20) null," + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table2) + " (" + "PlainChar char(20) null," + "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -309,13 +355,14 @@ private static void createTables() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table3 + " (" + "PlainBit bit null," + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table3) + " (" + "PlainBit bit null," + "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -419,25 +466,27 @@ private static void createTables() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table4 + " (" + "PlainInt int null," + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table4) + " (" + "PlainInt int null," + "RandomizedInt int ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicInt int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table5 + " (" + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table5) + " (" + "c1 int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "c2 smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -445,13 +494,14 @@ private static void createTables() throws SQLException { + "c3 bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table6 + " (" + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table6) + " (" + "c1 int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "c2 smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -459,7 +509,8 @@ private static void createTables() throws SQLException { + "c3 bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); @@ -467,10 +518,12 @@ private static void createTables() throws SQLException { } private static void populateTable4() throws SQLException { - String sql = "insert into " + table4 + " values( " + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(table4) + " values( " + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -482,12 +535,14 @@ private static void populateTable4() throws SQLException { } private static void populateTable3() throws SQLException { - String sql = "insert into " + table3 + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(table3) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -588,51 +643,60 @@ private static void populateTable3() throws SQLException { } private void createMultiInsertionSelection() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + multiStatementsProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + multiStatementsProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(multiStatementsProcedure) + + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure); - sql = "CREATE PROCEDURE " + multiStatementsProcedure - + " (@p0 char(20) = null, @p1 char(20) = null, @p2 char(20) = null, " - + "@p3 varchar(50) = null, @p4 varchar(50) = null, @p5 varchar(50) = null)" + " AS" + " INSERT INTO " - + table1 + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + " INSERT INTO " + table2 - + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + " SELECT * FROM " + table1 + " SELECT * FROM " + table2; - stmt.execute(sql); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure) + + " (@p0 char(20) = null, @p1 char(20) = null, @p2 char(20) = null, " + + "@p3 varchar(50) = null, @p4 varchar(50) = null, @p5 varchar(50) = null)" + " AS" + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(table1) + + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + " INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(table2) + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + + " SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(table1) + " SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(table2); + stmt.execute(sql); + } } private void MultiInsertionSelection() throws SQLException { - try { - String sql = "{call " + multiStatementsProcedure + " (?,?,?,?,?,?)}"; - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils - .getCallableStmt(con, sql, stmtColEncSetting)) { + String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure) + " (?,?,?,?,?,?)}"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { - // char, varchar - for (int i = 1; i <= 3; i++) { - callableStatement.setString(i, charValues[0]); - } + // char, varchar + for (int i = 1; i <= 3; i++) { + callableStatement.setString(i, charValues[0]); + } - for (int i = 4; i <= 6; i++) { - callableStatement.setString(i, charValues[1]); - } + for (int i = 4; i <= 6; i++) { + callableStatement.setString(i, charValues[1]); + } - boolean results = callableStatement.execute(); + boolean results = callableStatement.execute(); - // skip update count which is given by insertion - while (false == results && (-1) != callableStatement.getUpdateCount()) { - results = callableStatement.getMoreResults(); - } + // skip update count which is given by insertion + while (false == results && (-1) != callableStatement.getUpdateCount()) { + results = callableStatement.getMoreResults(); + } - while (results) { - try (ResultSet rs = callableStatement.getResultSet()) { - int numberOfColumns = rs.getMetaData().getColumnCount(); + while (results) { + try (ResultSet rs = callableStatement.getResultSet()) { + int numberOfColumns = rs.getMetaData().getColumnCount(); - while (rs.next()) { - testGetString(rs, numberOfColumns); - } + while (rs.next()) { + testGetString(rs, numberOfColumns); } - results = callableStatement.getMoreResults(); } + results = callableStatement.getMoreResults(); } } catch (SQLException e) { fail(e.toString()); @@ -654,28 +718,36 @@ private void testGetString(ResultSet rs, int numberOfColumns) throws SQLExceptio } private void createInputProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + inputProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + inputProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(inputProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + inputProcedure + " @p0 int, @p1 decimal(18, 0), " - + "@p2 float, @p3 real, @p4 numeric(18, 0), @p5 smallmoney, @p6 money," - + "@p7 bit, @p8 smallint, @p9 bigint, @p10 float(30), @p11 decimal(10,5), @p12 numeric(8,2), " - + "@p13 decimal(28,4), @p14 numeric(28,4) " + " AS" + " SELECT top 1 RandomizedInt FROM " - + numericTable + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p1 and " - + " DeterministicFloatDefault=@p2 and DeterministicReal=@p3 and DeterministicNumericDefault=@p4 and" - + " DeterministicSmallMoney=@p5 and DeterministicMoney=@p6 and DeterministicBit=@p7 and" - + " DeterministicSmallint=@p8 and DeterministicBigint=@p9 and DeterministicFloat=@p10 and" - + " DeterministicDecimal=@p11 and DeterministicNumeric=@p12 and DeterministicDecimal2=@p13 and" - + " DeterministicNumeric2=@p14 "; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure) + + " @p0 int, @p1 decimal(18, 0), " + + "@p2 float, @p3 real, @p4 numeric(18, 0), @p5 smallmoney, @p6 money," + + "@p7 bit, @p8 smallint, @p9 bigint, @p10 float(30), @p11 decimal(10,5), @p12 numeric(8,2), " + + "@p13 decimal(28,4), @p14 numeric(28,4) " + " AS" + " SELECT top 1 RandomizedInt FROM " + + AbstractSQLGenerator.escapeIdentifier(numericTable) + + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p1 and " + + " DeterministicFloatDefault=@p2 and DeterministicReal=@p3 and DeterministicNumericDefault=@p4 and" + + " DeterministicSmallMoney=@p5 and DeterministicMoney=@p6 and DeterministicBit=@p7 and" + + " DeterministicSmallint=@p8 and DeterministicBigint=@p9 and DeterministicFloat=@p10 and" + + " DeterministicDecimal=@p11 and DeterministicNumeric=@p12 and DeterministicDecimal2=@p13 and" + + " DeterministicNumeric2=@p14 "; - stmt.execute(sql); + stmt.execute(sql); + } } private void testInputProcedure(String sql, String[] values) throws SQLException { - - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(values[3])); if (RandomData.returnZero) @@ -712,24 +784,32 @@ private void testInputProcedure(String sql, String[] values) throws SQLException } private void createInputProcedure2() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + inputProcedure2 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + inputProcedure2; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(inputProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2); - sql = "CREATE PROCEDURE " + inputProcedure2 - + " @p0 varchar(50), @p1 uniqueidentifier, @p2 varchar(max), @p3 nchar(30), @p4 nvarchar(60), @p5 nvarchar(max), " - + " @p6 varchar(8000), @p7 nvarchar(4000)" + " AS" - + " SELECT top 1 RandomizedVarchar, DeterministicUniqueidentifier, DeterministicVarcharMax, RandomizedNchar, " - + " DeterministicNvarchar, DeterministicNvarcharMax, DeterministicVarchar8000, RandomizedNvarchar4000 FROM " - + charTable + " where DeterministicVarchar = @p0 and DeterministicUniqueidentifier =@p1"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2) + + " @p0 varchar(50), @p1 uniqueidentifier, @p2 varchar(max), @p3 nchar(30), @p4 nvarchar(60), @p5 nvarchar(max), " + + " @p6 varchar(8000), @p7 nvarchar(4000)" + " AS" + + " SELECT top 1 RandomizedVarchar, DeterministicUniqueidentifier, DeterministicVarcharMax, RandomizedNchar, " + + " DeterministicNvarchar, DeterministicNvarcharMax, DeterministicVarchar8000, RandomizedNvarchar4000 FROM " + + AbstractSQLGenerator.escapeIdentifier(charTable) + + " where DeterministicVarchar = @p0 and DeterministicUniqueidentifier =@p1"; + + stmt.execute(sql); + } } private void testInputProcedure2(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setString(1, charValues[1]); callableStatement.setUniqueIdentifier(2, charValues[6]); @@ -758,21 +838,29 @@ private void testInputProcedure2(String sql) throws SQLException { } private void createOutputProcedure3() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure3 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure3; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure3) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedure3 + " @p0 int OUTPUT, @p1 int OUTPUT " + " AS" - + " SELECT top 1 @p0=DeterministicInt FROM " + table3 + " SELECT top 1 @p1=RandomizedInt FROM " - + table4; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + + " @p0 int OUTPUT, @p1 int OUTPUT " + " AS" + " SELECT top 1 @p0=DeterministicInt FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " SELECT top 1 @p1=RandomizedInt FROM " + + AbstractSQLGenerator.escapeIdentifier(table4); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -800,8 +888,10 @@ private void testOutputProcedure3RandomOrder(String sql) throws SQLException { private void testOutputProcedure3Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -820,8 +910,10 @@ private void testOutputProcedure3Inorder(String sql) throws SQLException { private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -839,24 +931,31 @@ private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { } private void createOutputProcedure2() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure2 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure2; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedure2 - + " @p0 int OUTPUT, @p1 int OUTPUT, @p2 smallint OUTPUT, @p3 smallint OUTPUT, @p4 tinyint OUTPUT, @p5 tinyint OUTPUT, @p6 smallmoney OUTPUT," - + " @p7 smallmoney OUTPUT, @p8 money OUTPUT, @p9 money OUTPUT " + " AS" - + " SELECT top 1 @p0=PlainInt, @p1=DeterministicInt, @p2=PlainSmallint," - + " @p3=RandomizedSmallint, @p4=PlainTinyint, @p5=DeterministicTinyint, @p6=DeterministicSmallMoney, @p7=PlainSmallMoney," - + " @p8=PlainMoney, @p9=DeterministicMoney FROM " + table3; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + + " @p0 int OUTPUT, @p1 int OUTPUT, @p2 smallint OUTPUT, @p3 smallint OUTPUT, @p4 tinyint OUTPUT, @p5 tinyint OUTPUT, @p6 smallmoney OUTPUT," + + " @p7 smallmoney OUTPUT, @p8 money OUTPUT, @p9 money OUTPUT " + " AS" + + " SELECT top 1 @p0=PlainInt, @p1=DeterministicInt, @p2=PlainSmallint," + + " @p3=RandomizedSmallint, @p4=PlainTinyint, @p5=DeterministicTinyint, @p6=DeterministicSmallMoney, @p7=PlainSmallMoney," + + " @p8=PlainMoney, @p9=DeterministicMoney FROM " + AbstractSQLGenerator.escapeIdentifier(table3); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedure2RandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -907,8 +1006,10 @@ private void testOutputProcedure2RandomOrder(String sql, String[] values) throws private void testOutputProcedure2Inorder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -959,8 +1060,10 @@ private void testOutputProcedure2Inorder(String sql, String[] values) throws SQL private void testOutputProcedure2ReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -1010,23 +1113,31 @@ private void testOutputProcedure2ReverseOrder(String sql, String[] values) throw } private void createOutputProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure); - sql = "CREATE PROCEDURE " + outputProcedure + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, " - + "@p3 bigint OUTPUT, @p4 tinyint OUTPUT, @p5 smallmoney OUTPUT, @p6 money OUTPUT " + " AS" - + " SELECT top 1 @p0=RandomizedInt, @p1=DeterministicFloatDefault, @p2=RandomizedSmallint," - + " @p3=RandomizedBigint, @p4=DeterministicTinyint, @p5=DeterministicSmallMoney, @p6=DeterministicMoney FROM " - + table3; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, " + + "@p3 bigint OUTPUT, @p4 tinyint OUTPUT, @p5 smallmoney OUTPUT, @p6 money OUTPUT " + " AS" + + " SELECT top 1 @p0=RandomizedInt, @p1=DeterministicFloatDefault, @p2=RandomizedSmallint," + + " @p3=RandomizedBigint, @p4=DeterministicTinyint, @p5=DeterministicSmallMoney, @p6=DeterministicMoney FROM " + + AbstractSQLGenerator.escapeIdentifier(table3); + + stmt.execute(sql); + } } private void testOutputProcedureRandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1073,8 +1184,10 @@ private void testOutputProcedureRandomOrder(String sql, String[] values) throws private void testOutputProcedureInorder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1114,8 +1227,10 @@ private void testOutputProcedureInorder(String sql, String[] values) throws SQLE private void testOutputProcedureReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1153,20 +1268,28 @@ private void testOutputProcedureReverseOrder(String sql, String[] values) throws } private void createInOutProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + inoutProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + inoutProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(inoutProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + inoutProcedure + " @p0 int OUTPUT" + " AS" - + " SELECT top 1 @p0=DeterministicInt FROM " + table3 + " where DeterministicInt=@p0"; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure) + " @p0 int OUTPUT" + + " AS" + " SELECT top 1 @p0=DeterministicInt FROM " + AbstractSQLGenerator.escapeIdentifier(table3) + + " where DeterministicInt=@p0"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testInOutProcedure(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(numericValues[3])); callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1181,21 +1304,30 @@ private void testInOutProcedure(String sql) throws SQLException { } private void createMixedProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + mixedProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure); - sql = "CREATE PROCEDURE " + mixedProcedure + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 decimal " + " AS" - + " SELECT top 1 @p0=DeterministicInt2, @p1=RandomizedFloatDefault FROM " + table3 - + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p3" + " return 123"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 decimal " + " AS" + + " SELECT top 1 @p0=DeterministicInt2, @p1=RandomizedFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p3" + " return 123"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedure(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.setInt(2, Integer.parseInt(numericValues[3])); @@ -1221,21 +1353,30 @@ private void testMixedProcedure(String sql) throws SQLException { } private void createMixedProcedure2() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedure2 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + mixedProcedure2; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2); - sql = "CREATE PROCEDURE " + mixedProcedure2 + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 int, @p4 float " + " AS" - + " SELECT top 1 @p0=DeterministicInt, @p1=PlainFloatDefault FROM " + table3 - + " where PlainInt=@p3 and DeterministicFloatDefault=@p4"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 int, @p4 float " + " AS" + + " SELECT top 1 @p0=DeterministicInt, @p1=PlainFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + + " where PlainInt=@p3 and DeterministicFloatDefault=@p4"; + + stmt.execute(sql); + } } private void testMixedProcedure2RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1268,8 +1409,10 @@ private void testMixedProcedure2RandomOrder(String sql) throws SQLException { private void testMixedProcedure2Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1288,22 +1431,29 @@ private void testMixedProcedure2Inorder(String sql) throws SQLException { } private void createMixedProcedure3() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedure3 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + mixedProcedure3; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedure3) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3); - sql = "CREATE PROCEDURE " + mixedProcedure3 - + " @p0 bigint OUTPUT, @p1 float OUTPUT, @p2 int OUTPUT, @p3 smallint" + " AS" - + " SELECT top 1 @p0=PlainBigint, @p1=PlainFloatDefault FROM " + table3 - + " where PlainInt=@p2 and PlainSmallint=@p3"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + + " @p0 bigint OUTPUT, @p1 float OUTPUT, @p2 int OUTPUT, @p3 smallint" + " AS" + + " SELECT top 1 @p0=PlainBigint, @p1=PlainFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " where PlainInt=@p2 and PlainSmallint=@p3"; + + stmt.execute(sql); + } } private void testMixedProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1336,8 +1486,10 @@ private void testMixedProcedure3RandomOrder(String sql) throws SQLException { private void testMixedProcedure3Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1357,8 +1509,10 @@ private void testMixedProcedure3Inorder(String sql) throws SQLException { private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1377,24 +1531,32 @@ private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { } private void createMixedProcedureNumericPrcisionScale() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedureNumericPrcisionScale + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedureNumericPrcisionScale) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " - + mixedProcedureNumericPrcisionScale; - stmt.execute(sql); + + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + mixedProcedureNumericPrcisionScale - + " @p1 decimal(18,0) OUTPUT, @p2 decimal(10,5) OUTPUT, @p3 numeric(18, 0) OUTPUT, @p4 numeric(8,2) OUTPUT " - + " AS" + " SELECT top 1 @p1=RandomizedDecimalDefault, @p2=DeterministicDecimal," - + " @p3=RandomizedNumericDefault, @p4=DeterministicNumeric FROM " + table3 - + " where DeterministicDecimal=@p2 and DeterministicNumeric=@p4" + " return 123"; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale) + + " @p1 decimal(18,0) OUTPUT, @p2 decimal(10,5) OUTPUT, @p3 numeric(18, 0) OUTPUT, @p4 numeric(8,2) OUTPUT " + + " AS" + " SELECT top 1 @p1=RandomizedDecimalDefault, @p2=DeterministicDecimal," + + " @p3=RandomizedNumericDefault, @p4=DeterministicNumeric FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + + " where DeterministicDecimal=@p2 and DeterministicNumeric=@p4" + " return 123"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter(2, java.sql.Types.DECIMAL, 10, 5); @@ -1423,8 +1585,10 @@ private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter("p1", java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter("p2", java.sql.Types.DECIMAL, 10, 5); @@ -1452,25 +1616,33 @@ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) thr } private void createOutputProcedureChar() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureChar - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureChar; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureChar) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar); - sql = "CREATE PROCEDURE " + outputProcedureChar - + " @p0 char(20) OUTPUT,@p1 varchar(50) OUTPUT,@p2 nchar(30) OUTPUT," - + "@p3 nvarchar(60) OUTPUT, @p4 uniqueidentifier OUTPUT, @p5 varchar(max) OUTPUT, @p6 nvarchar(max) OUTPUT, @p7 varchar(8000) OUTPUT, @p8 nvarchar(4000) OUTPUT" - + " AS" + " SELECT top 1 @p0=DeterministicChar,@p1=RandomizedVarChar,@p2=RandomizedNChar," - + " @p3=DeterministicNVarChar, @p4=DeterministicUniqueidentifier, @p5=DeterministicVarcharMax," - + " @p6=DeterministicNvarcharMax, @p7=DeterministicVarchar8000, @p8=RandomizedNvarchar4000 FROM " - + charTable; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar) + + " @p0 char(20) OUTPUT,@p1 varchar(50) OUTPUT,@p2 nchar(30) OUTPUT," + + "@p3 nvarchar(60) OUTPUT, @p4 uniqueidentifier OUTPUT, @p5 varchar(max) OUTPUT, @p6 nvarchar(max) OUTPUT, @p7 varchar(8000) OUTPUT, @p8 nvarchar(4000) OUTPUT" + + " AS" + " SELECT top 1 @p0=DeterministicChar,@p1=RandomizedVarChar,@p2=RandomizedNChar," + + " @p3=DeterministicNVarChar, @p4=DeterministicUniqueidentifier, @p5=DeterministicVarcharMax," + + " @p6=DeterministicNvarcharMax, @p7=DeterministicVarchar8000, @p8=RandomizedNvarchar4000 FROM " + + AbstractSQLGenerator.escapeIdentifier(charTable); + + stmt.execute(sql); + } } private void testOutputProcedureCharInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + 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); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1517,8 +1689,11 @@ private void testOutputProcedureCharInorder(String sql) throws SQLException { private void testOutputProcedureCharInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + 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); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1567,27 +1742,37 @@ private void testOutputProcedureCharInorderObject(String sql) throws SQLExceptio } private void createOutputProcedureNumeric() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureNumeric - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureNumeric; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureNumeric) + + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric); - sql = "CREATE PROCEDURE " + outputProcedureNumeric - + " @p0 bit OUTPUT, @p1 tinyint OUTPUT, @p2 smallint OUTPUT, @p3 int OUTPUT," - + " @p4 bigint OUTPUT, @p5 float OUTPUT, @p6 float(30) output, @p7 real output, @p8 decimal(18, 0) output, @p9 decimal(10,5) output," - + " @p10 numeric(18, 0) output, @p11 numeric(8,2) output, @p12 smallmoney output, @p13 money output, @p14 decimal(28,4) output, @p15 numeric(28,4) output" - + " AS" + " SELECT top 1 @p0=DeterministicBit, @p1=RandomizedTinyint, @p2=DeterministicSmallint," - + " @p3=RandomizedInt, @p4=DeterministicBigint, @p5=RandomizedFloatDefault, @p6=DeterministicFloat," - + " @p7=RandomizedReal, @p8=DeterministicDecimalDefault, @p9=RandomizedDecimal," - + " @p10=DeterministicNumericDefault, @p11=RandomizedNumeric, @p12=RandomizedSmallMoney, @p13=DeterministicMoney," - + " @p14=DeterministicDecimal2, @p15=DeterministicNumeric2 FROM " + numericTable; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric) + + " @p0 bit OUTPUT, @p1 tinyint OUTPUT, @p2 smallint OUTPUT, @p3 int OUTPUT," + + " @p4 bigint OUTPUT, @p5 float OUTPUT, @p6 float(30) output, @p7 real output, @p8 decimal(18, 0) output, @p9 decimal(10,5) output," + + " @p10 numeric(18, 0) output, @p11 numeric(8,2) output, @p12 smallmoney output, @p13 money output, @p14 decimal(28,4) output, @p15 numeric(28,4) output" + + " AS" + " SELECT top 1 @p0=DeterministicBit, @p1=RandomizedTinyint, @p2=DeterministicSmallint," + + " @p3=RandomizedInt, @p4=DeterministicBigint, @p5=RandomizedFloatDefault, @p6=DeterministicFloat," + + " @p7=RandomizedReal, @p8=DeterministicDecimalDefault, @p9=RandomizedDecimal," + + " @p10=DeterministicNumericDefault, @p11=RandomizedNumeric, @p12=RandomizedSmallMoney, @p13=DeterministicMoney," + + " @p14=DeterministicDecimal2, @p15=DeterministicNumeric2 FROM " + + AbstractSQLGenerator.escapeIdentifier(numericTable); + + stmt.execute(sql); + } } private void testOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.BIT); callableStatement.registerOutParameter(2, java.sql.Types.TINYINT); callableStatement.registerOutParameter(3, java.sql.Types.SMALLINT); @@ -1673,8 +1858,11 @@ private void testOutputProcedureNumericInorder(String sql) throws SQLException { private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.BIT); callableStatement.registerOutParameter(2, java.sql.Types.TINYINT); callableStatement.registerOutParameter(3, java.sql.Types.SMALLINT); @@ -1953,23 +2141,32 @@ private Object getxxx(int ordinal, Class coercion, } private void createOutputProcedureBinary() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureBinary - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureBinary; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureBinary) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedureBinary - + " @p0 binary(20) OUTPUT,@p1 varbinary(50) OUTPUT,@p2 varbinary(max) OUTPUT," - + " @p3 binary(512) OUTPUT,@p4 varbinary(8000) OUTPUT " + " AS" - + " SELECT top 1 @p0=RandomizedBinary,@p1=DeterministicVarbinary,@p2=DeterministicVarbinaryMax," - + " @p3=DeterministicBinary512,@p4=DeterministicBinary8000 FROM " + binaryTable; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + + " @p0 binary(20) OUTPUT,@p1 varbinary(50) OUTPUT,@p2 varbinary(max) OUTPUT," + + " @p3 binary(512) OUTPUT,@p4 varbinary(8000) OUTPUT " + " AS" + + " SELECT top 1 @p0=RandomizedBinary,@p1=DeterministicVarbinary,@p2=DeterministicVarbinaryMax," + + " @p3=DeterministicBinary512,@p4=DeterministicBinary8000 FROM " + + AbstractSQLGenerator.escapeIdentifier(binaryTable); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureBinaryInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + 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); callableStatement.registerOutParameter(3, java.sql.Types.LONGVARBINARY); @@ -2014,8 +2211,11 @@ private void testOutputProcedureBinaryInorder(String sql) throws SQLException { private void testOutputProcedureBinaryInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + 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); callableStatement.registerOutParameter(3, java.sql.Types.LONGVARBINARY); @@ -2053,8 +2253,11 @@ private void testOutputProcedureBinaryInorderObject(String sql) throws SQLExcept private void testOutputProcedureBinaryInorderString(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + 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); callableStatement.registerOutParameter(3, java.sql.Types.LONGVARBINARY); @@ -2090,7 +2293,7 @@ private void testOutputProcedureBinaryInorderString(String sql) throws SQLExcept } protected static void createDateTableCallableStatement() throws SQLException { - String sql = "create table " + dateTable + " (" + "PlainDate date null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + "PlainDate date null," + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicDate date ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -2146,7 +2349,8 @@ protected static void createDateTableCallableStatement() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -2182,83 +2386,95 @@ private static LinkedList createTemporalTypesCallableStatement(boolean n } private static void populateDateNormalCase() throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { - // date - for (int i = 1; i <= 3; i++) { - sqlPstmt.setDate(i, (Date) dateValues.get(0)); - } + // date + for (int i = 1; i <= 3; i++) { + sqlPstmt.setDate(i, (Date) dateValues.get(0)); + } - // datetime2 default - for (int i = 4; i <= 6; i++) { - sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); - } + // datetime2 default + for (int i = 4; i <= 6; i++) { + sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); + } - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); - } + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); + } - // time default - for (int i = 10; i <= 12; i++) { - sqlPstmt.setTime(i, (Time) dateValues.get(3)); - } + // time default + for (int i = 10; i <= 12; i++) { + sqlPstmt.setTime(i, (Time) dateValues.get(3)); + } - // datetime2(2) - for (int i = 13; i <= 15; i++) { - sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); - } + // datetime2(2) + for (int i = 13; i <= 15; i++) { + sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); + } - // time(2) - for (int i = 16; i <= 18; i++) { - sqlPstmt.setTime(i, (Time) dateValues.get(5), 2); - } + // time(2) + for (int i = 16; i <= 18; i++) { + sqlPstmt.setTime(i, (Time) dateValues.get(5), 2); + } - // datetimeoffset(2) - for (int i = 19; i <= 21; i++) { - sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); - } + // datetimeoffset(2) + for (int i = 19; i <= 21; i++) { + sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); + } - // datetime() - for (int i = 22; i <= 24; i++) { - sqlPstmt.setDateTime(i, (Timestamp) dateValues.get(7)); - } + // datetime() + for (int i = 22; i <= 24; i++) { + sqlPstmt.setDateTime(i, (Timestamp) dateValues.get(7)); + } - // smalldatetime() - for (int i = 25; i <= 27; i++) { - sqlPstmt.setSmallDateTime(i, (Timestamp) dateValues.get(8)); + // smalldatetime() + for (int i = 25; i <= 27; i++) { + sqlPstmt.setSmallDateTime(i, (Timestamp) dateValues.get(8)); + } + sqlPstmt.execute(); } - sqlPstmt.execute(); } private void createOutputProcedureDate() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureDate - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureDate; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureDate) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedureDate - + " @p0 date OUTPUT, @p01 date OUTPUT, @p1 datetime2 OUTPUT, @p11 datetime2 OUTPUT," - + " @p2 datetimeoffset OUTPUT, @p21 datetimeoffset OUTPUT, @p3 time OUTPUT, @p31 time OUTPUT, @p4 datetime OUTPUT, @p41 datetime OUTPUT," - + " @p5 smalldatetime OUTPUT, @p51 smalldatetime OUTPUT, @p6 datetime2(2) OUTPUT, @p61 datetime2(2) OUTPUT, @p7 time(2) OUTPUT, @p71 time(2) OUTPUT, " - + " @p8 datetimeoffset(2) OUTPUT, @p81 datetimeoffset(2) OUTPUT " + " AS" - + " SELECT top 1 @p0=PlainDate,@p01=RandomizedDate,@p1=PlainDatetime2Default,@p11=RandomizedDatetime2Default," - + " @p2=PlainDatetimeoffsetDefault,@p21=DeterministicDatetimeoffsetDefault," - + " @p3=PlainTimeDefault,@p31=DeterministicTimeDefault," - + " @p4=PlainDateTime,@p41=DeterministicDateTime, @p5=PlainSmallDateTime,@p51=RandomizedSmallDateTime, " - + " @p6=PlainDatetime2,@p61=RandomizedDatetime2, @p7=PlainTime,@p71=Deterministictime, " - + " @p8=PlainDatetimeoffset, @p81=RandomizedDatetimeoffset" + " FROM " + dateTable; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate) + + " @p0 date OUTPUT, @p01 date OUTPUT, @p1 datetime2 OUTPUT, @p11 datetime2 OUTPUT," + + " @p2 datetimeoffset OUTPUT, @p21 datetimeoffset OUTPUT, @p3 time OUTPUT, @p31 time OUTPUT, @p4 datetime OUTPUT, @p41 datetime OUTPUT," + + " @p5 smalldatetime OUTPUT, @p51 smalldatetime OUTPUT, @p6 datetime2(2) OUTPUT, @p61 datetime2(2) OUTPUT, @p7 time(2) OUTPUT, @p71 time(2) OUTPUT, " + + " @p8 datetimeoffset(2) OUTPUT, @p81 datetimeoffset(2) OUTPUT " + " AS" + + " SELECT top 1 @p0=PlainDate,@p01=RandomizedDate,@p1=PlainDatetime2Default,@p11=RandomizedDatetime2Default," + + " @p2=PlainDatetimeoffsetDefault,@p21=DeterministicDatetimeoffsetDefault," + + " @p3=PlainTimeDefault,@p31=DeterministicTimeDefault," + + " @p4=PlainDateTime,@p41=DeterministicDateTime, @p5=PlainSmallDateTime,@p51=RandomizedSmallDateTime, " + + " @p6=PlainDatetime2,@p61=RandomizedDatetime2, @p7=PlainTime,@p71=Deterministictime, " + + " @p8=PlainDatetimeoffset, @p81=RandomizedDatetimeoffset" + " FROM " + + AbstractSQLGenerator.escapeIdentifier(dateTable); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureDateInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2309,8 +2525,11 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { private void testOutputProcedureDateInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2360,25 +2579,34 @@ private void testOutputProcedureDateInorderObject(String sql) throws SQLExceptio } private void createOutputProcedureBatch() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureBatch - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureBatch; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureBatch) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - // If a procedure contains more than one SQL statement, it is considered - // to be a batch of SQL statements. - sql = "CREATE PROCEDURE " + outputProcedureBatch - + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, @p3 smallmoney OUTPUT " + " AS" - + " select top 1 @p0=RandomizedInt FROM " + table3 + " select top 1 @p1=DeterministicFloatDefault FROM " - + table3 + " select top 1 @p2=RandomizedSmallint FROM " + table3 - + " select top 1 @p3=DeterministicSmallMoney FROM " + table3; + // If a procedure contains more than one SQL statement, it is considered + // to be a batch of SQL statements. + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, @p3 smallmoney OUTPUT " + " AS" + + " select top 1 @p0=RandomizedInt FROM " + AbstractSQLGenerator.escapeIdentifier(table3) + + " select top 1 @p1=DeterministicFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " select top 1 @p2=RandomizedSmallint FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " select top 1 @p3=DeterministicSmallMoney FROM " + + AbstractSQLGenerator.escapeIdentifier(table3); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureBatchInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -2403,39 +2631,57 @@ private void testOutputProcedureBatchInorder(String sql) throws SQLException { } private void createOutputProcedure4() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure4 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure4; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure4) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure4); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "create procedure " + outputProcedure4 - + " @in1 int, @in2 smallint, @in3 bigint, @in4 int, @in5 smallint, @in6 bigint, @out1 int output, @out2 smallint output, @out3 bigint output, @out4 int output, @out5 smallint output, @out6 bigint output" - + " as " + " insert into " + table5 + " values (@in1, @in2, @in3)" + " insert into " + table6 - + " values (@in4, @in5, @in6)" + " select * from " + table5 + " select * from " + table6 - + " select @out1 = c1, @out2=c2, @out3=c3 from " + table5 - + " select @out4 = c1, @out5=c2, @out6=c3 from " + table6; + sql = "create procedure " + AbstractSQLGenerator.escapeIdentifier(outputProcedure4) + + " @in1 int, @in2 smallint, @in3 bigint, @in4 int, @in5 smallint, @in6 bigint, @out1 int output, @out2 smallint output, @out3 bigint output, @out4 int output, @out5 smallint output, @out6 bigint output" + + " as " + " insert into " + AbstractSQLGenerator.escapeIdentifier(table5) + + " values (@in1, @in2, @in3)" + " insert into " + AbstractSQLGenerator.escapeIdentifier(table6) + + " values (@in4, @in5, @in6)" + " select * from " + AbstractSQLGenerator.escapeIdentifier(table5) + + " select * from " + AbstractSQLGenerator.escapeIdentifier(table6) + + " select @out1 = c1, @out2=c2, @out3=c3 from " + AbstractSQLGenerator.escapeIdentifier(table5) + + " select @out4 = c1, @out5=c2, @out6=c3 from " + AbstractSQLGenerator.escapeIdentifier(table6); - stmt.execute(sql); + stmt.execute(sql); + } } private void createMixedProcedureDateScale() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + MixedProcedureDateScale - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + MixedProcedureDateScale; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureDateScale) + + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + MixedProcedureDateScale + " @p1 datetime2(2) OUTPUT, @p2 datetime2(2) OUTPUT," - + " @p3 time(2) OUTPUT, @p4 time(2) OUTPUT, @p5 datetimeoffset(2) OUTPUT, @p6 datetimeoffset(2) OUTPUT " - + " AS" - + " SELECT top 1 @p1=DeterministicDatetime2,@p2=RandomizedDatetime2,@p3=DeterministicTime,@p4=RandomizedTime," - + " @p5=DeterministicDatetimeoffset,@p6=RandomizedDatetimeoffset " + " FROM " + scaleDateTable - + " where DeterministicDatetime2 = @p1 and DeterministicTime = @p3 and DeterministicDatetimeoffset=@p5"; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale) + + " @p1 datetime2(2) OUTPUT, @p2 datetime2(2) OUTPUT," + + " @p3 time(2) OUTPUT, @p4 time(2) OUTPUT, @p5 datetimeoffset(2) OUTPUT, @p6 datetimeoffset(2) OUTPUT " + + " AS" + + " SELECT top 1 @p1=DeterministicDatetime2,@p2=RandomizedDatetime2,@p3=DeterministicTime,@p4=RandomizedTime," + + " @p5=DeterministicDatetimeoffset,@p6=RandomizedDatetimeoffset " + " FROM " + + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + + " where DeterministicDatetime2 = @p1 and DeterministicTime = @p3 and DeterministicDatetimeoffset=@p5"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedureDateScaleInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter(2, java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter(3, java.sql.Types.TIME, 2); @@ -2463,8 +2709,11 @@ private void testMixedProcedureDateScaleInorder(String sql) throws SQLException private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter("p1", java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter("p2", java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter("p3", java.sql.Types.TIME, 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 0448f3fff..b145dc989 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -18,11 +19,13 @@ import org.opentest4j.TestAbortedException; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; 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.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; /** @@ -51,12 +54,15 @@ public class JDBCEncryptionDecryptionTest extends AESetup { */ @Test public void testCharSpecificSetter() throws SQLException { - charValues = createCharValues(nullable); - dropTables(stmt); - createCharTable(); - populateCharNormalCase(charValues); - testChar(stmt, charValues); - testChar(null, charValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + charValues = createCharValues(nullable); + dropTables(stmt); + createCharTable(); + populateCharNormalCase(charValues); + testChar(stmt, charValues); + testChar(null, charValues); + } } /** @@ -66,12 +72,15 @@ public void testCharSpecificSetter() throws SQLException { */ @Test public void testCharSetObject() throws SQLException { - charValues = createCharValues(nullable); - dropTables(stmt); - createCharTable(); - populateCharSetObject(charValues); - testChar(stmt, charValues); - testChar(null, charValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + charValues = createCharValues(nullable); + dropTables(stmt); + createCharTable(); + populateCharSetObject(charValues); + testChar(stmt, charValues); + testChar(null, charValues); + } } /** @@ -83,12 +92,15 @@ public void testCharSetObject() throws SQLException { public void testCharSetObjectWithJDBCTypes() throws SQLException { skipTestForJava7(); - charValues = createCharValues(nullable); - dropTables(stmt); - createCharTable(); - populateCharSetObjectWithJDBCTypes(charValues); - testChar(stmt, charValues); - testChar(null, charValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + charValues = createCharValues(nullable); + dropTables(stmt); + createCharTable(); + populateCharSetObjectWithJDBCTypes(charValues); + testChar(stmt, charValues); + testChar(null, charValues); + } } /** @@ -98,12 +110,15 @@ public void testCharSetObjectWithJDBCTypes() throws SQLException { */ @Test public void testCharSpecificSetterNull() throws SQLException { - String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; - dropTables(stmt); - createCharTable(); - populateCharNormalCase(charValuesNull); - testChar(stmt, charValuesNull); - testChar(null, charValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; + dropTables(stmt); + createCharTable(); + populateCharNormalCase(charValuesNull); + testChar(stmt, charValuesNull); + testChar(null, charValuesNull); + } } /** @@ -113,12 +128,15 @@ public void testCharSpecificSetterNull() throws SQLException { */ @Test public void testCharSetObjectNull() throws SQLException { - String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; - dropTables(stmt); - createCharTable(); - populateCharSetObject(charValuesNull); - testChar(stmt, charValuesNull); - testChar(null, charValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; + dropTables(stmt); + createCharTable(); + populateCharSetObject(charValuesNull); + testChar(stmt, charValuesNull); + testChar(null, charValuesNull); + } } /** @@ -128,12 +146,15 @@ public void testCharSetObjectNull() throws SQLException { */ @Test public void testCharSetNull() throws SQLException { - String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; - dropTables(stmt); - createCharTable(); - populateCharNullCase(); - testChar(stmt, charValuesNull); - testChar(null, charValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; + dropTables(stmt); + createCharTable(); + populateCharNullCase(); + testChar(stmt, charValuesNull); + testChar(null, charValuesNull); + } } /** @@ -143,12 +164,15 @@ public void testCharSetNull() throws SQLException { */ @Test public void testBinarySpecificSetter() throws SQLException { - LinkedList byteValues = createbinaryValues(false); - dropTables(stmt); - createBinaryTable(); - populateBinaryNormalCase(byteValues); - testBinary(stmt, byteValues); - testBinary(null, byteValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + LinkedList byteValues = createbinaryValues(false); + dropTables(stmt); + createBinaryTable(); + populateBinaryNormalCase(byteValues); + testBinary(stmt, byteValues); + testBinary(null, byteValues); + } } /** @@ -158,12 +182,15 @@ public void testBinarySpecificSetter() throws SQLException { */ @Test public void testBinarySetobject() throws SQLException { - byteValuesSetObject = createbinaryValues(false); - dropTables(stmt); - createBinaryTable(); - populateBinarySetObject(byteValuesSetObject); - testBinary(stmt, byteValuesSetObject); - testBinary(null, byteValuesSetObject); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesSetObject = createbinaryValues(false); + dropTables(stmt); + createBinaryTable(); + populateBinarySetObject(byteValuesSetObject); + testBinary(stmt, byteValuesSetObject); + testBinary(null, byteValuesSetObject); + } } /** @@ -173,12 +200,15 @@ public void testBinarySetobject() throws SQLException { */ @Test public void testBinarySetNull() throws SQLException { - byteValuesNull = createbinaryValues(true); - dropTables(stmt); - createBinaryTable(); - populateBinaryNullCase(); - testBinary(stmt, byteValuesNull); - testBinary(null, byteValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesNull = createbinaryValues(true); + dropTables(stmt); + createBinaryTable(); + populateBinaryNullCase(); + testBinary(stmt, byteValuesNull); + testBinary(null, byteValuesNull); + } } /** @@ -188,12 +218,15 @@ public void testBinarySetNull() throws SQLException { */ @Test public void testBinarySpecificSetterNull() throws SQLException { - byteValuesNull = createbinaryValues(true); - dropTables(stmt); - createBinaryTable(); - populateBinaryNormalCase(null); - testBinary(stmt, byteValuesNull); - testBinary(null, byteValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesNull = createbinaryValues(true); + dropTables(stmt); + createBinaryTable(); + populateBinaryNormalCase(null); + testBinary(stmt, byteValuesNull); + testBinary(null, byteValuesNull); + } } /** @@ -203,12 +236,15 @@ public void testBinarySpecificSetterNull() throws SQLException { */ @Test public void testBinarysetObjectNull() throws SQLException { - byteValuesNull = createbinaryValues(true); - dropTables(stmt); - createBinaryTable(); - populateBinarySetObject(null); - testBinary(stmt, byteValuesNull); - testBinary(null, byteValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesNull = createbinaryValues(true); + dropTables(stmt); + createBinaryTable(); + populateBinarySetObject(null); + testBinary(stmt, byteValuesNull); + testBinary(null, byteValuesNull); + } } /** @@ -220,12 +256,15 @@ public void testBinarysetObjectNull() throws SQLException { public void testBinarySetObjectWithJDBCTypes() throws SQLException { skipTestForJava7(); - byteValuesSetObject = createbinaryValues(false); - dropTables(stmt); - createBinaryTable(); - populateBinarySetObjectWithJDBCType(byteValuesSetObject); - testBinary(stmt, byteValuesSetObject); - testBinary(null, byteValuesSetObject); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesSetObject = createbinaryValues(false); + dropTables(stmt); + createBinaryTable(); + populateBinarySetObjectWithJDBCType(byteValuesSetObject); + testBinary(stmt, byteValuesSetObject); + testBinary(null, byteValuesSetObject); + } } /** @@ -235,12 +274,15 @@ public void testBinarySetObjectWithJDBCTypes() throws SQLException { */ @Test public void testDateSpecificSetter() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateNormalCase(dateValues); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateNormalCase(dateValues); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -250,12 +292,15 @@ public void testDateSpecificSetter() throws SQLException { */ @Test public void testDateSetObject() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObject(dateValues, ""); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObject(dateValues, ""); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -265,12 +310,15 @@ public void testDateSetObject() throws SQLException { */ @Test public void testDateSetObjectWithJavaType() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObject(dateValues, "setwithJavaType"); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObject(dateValues, "setwithJavaType"); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -280,12 +328,15 @@ public void testDateSetObjectWithJavaType() throws SQLException { */ @Test public void testDateSetObjectWithJDBCType() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObject(dateValues, "setwithJDBCType"); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObject(dateValues, "setwithJDBCType"); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -295,13 +346,16 @@ public void testDateSetObjectWithJDBCType() throws SQLException { */ @Test public void testDateSpecificSetterMinMaxValue() throws SQLException { - RandomData.returnMinMax = true; - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateNormalCase(dateValues); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + RandomData.returnMinMax = true; + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateNormalCase(dateValues); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -311,15 +365,18 @@ public void testDateSpecificSetterMinMaxValue() throws SQLException { */ @Test public void testDateSetNull() throws SQLException { - RandomData.returnNull = true; - nullable = true; - - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateNullCase(); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + RandomData.returnNull = true; + nullable = true; + + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateNullCase(); + testDate(stmt, dateValues); + testDate(null, dateValues); + } nullable = false; RandomData.returnNull = false; @@ -335,12 +392,15 @@ public void testDateSetObjectNull() throws SQLException { RandomData.returnNull = true; nullable = true; - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObjectNull(); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObjectNull(); + testDate(stmt, dateValues); + testDate(null, dateValues); + } nullable = false; RandomData.returnNull = false; @@ -357,11 +417,14 @@ public void testNumericSpecificSetter() throws TestAbortedException, Exception { numericValues2 = new String[numericValues.length]; System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - dropTables(stmt); - createNumericTable(); - populateNumeric(numericValues); - testNumeric(stmt, numericValues, false); - testNumeric(null, numericValues2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumeric(numericValues); + testNumeric(stmt, numericValues, false); + testNumeric(null, numericValues2, false); + } } /** @@ -375,11 +438,14 @@ public void testNumericSetObject() throws SQLException { numericValues2 = new String[numericValues.length]; System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - dropTables(stmt); - createNumericTable(); - populateNumericSetObject(numericValues); - testNumeric(null, numericValues, false); - testNumeric(stmt, numericValues2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericSetObject(numericValues); + testNumeric(null, numericValues, false); + testNumeric(stmt, numericValues2, false); + } } /** @@ -391,15 +457,18 @@ public void testNumericSetObject() throws SQLException { public void testNumericSetObjectWithJDBCTypes() throws SQLException { skipTestForJava7(); - numericValues = createNumericValues(nullable); - numericValues2 = new String[numericValues.length]; - System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - - dropTables(stmt); - createNumericTable(); - populateNumericSetObjectWithJDBCTypes(numericValues); - testNumeric(stmt, numericValues, false); - testNumeric(null, numericValues2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + numericValues = createNumericValues(nullable); + numericValues2 = new String[numericValues.length]; + System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); + + dropTables(stmt); + createNumericTable(); + populateNumericSetObjectWithJDBCTypes(numericValues); + testNumeric(stmt, numericValues, false); + testNumeric(null, numericValues2, false); + } } /** @@ -418,11 +487,14 @@ public void testNumericSpecificSetterMaxValue() throws SQLException { "214748.3647", "922337203685477.5807", "999999999999999999999999.9999", "999999999999999999999999.9999"}; - dropTables(stmt); - createNumericTable(); - populateNumeric(numericValuesBoundaryPositive); - testNumeric(stmt, numericValuesBoundaryPositive, false); - testNumeric(null, numericValuesBoundaryPositive2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumeric(numericValuesBoundaryPositive); + testNumeric(stmt, numericValuesBoundaryPositive, false); + testNumeric(null, numericValuesBoundaryPositive2, false); + } } /** @@ -441,11 +513,14 @@ public void testNumericSpecificSetterMinValue() throws SQLException { "-214748.3648", "-922337203685477.5808", "999999999999999999999999.9999", "999999999999999999999999.9999"}; - dropTables(stmt); - createNumericTable(); - populateNumeric(numericValuesBoundaryNegtive); - testNumeric(stmt, numericValuesBoundaryNegtive, false); - testNumeric(null, numericValuesBoundaryNegtive2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumeric(numericValuesBoundaryNegtive); + testNumeric(stmt, numericValuesBoundaryNegtive, false); + testNumeric(null, numericValuesBoundaryNegtive2, false); + } } /** @@ -461,11 +536,14 @@ public void testNumericSpecificSetterNull() throws SQLException { numericValuesNull2 = new String[numericValuesNull.length]; System.arraycopy(numericValuesNull, 0, numericValuesNull2, 0, numericValuesNull.length); - dropTables(stmt); - createNumericTable(); - populateNumericNullCase(numericValuesNull); - testNumeric(stmt, numericValuesNull, true); - testNumeric(null, numericValuesNull2, true); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericNullCase(numericValuesNull); + testNumeric(stmt, numericValuesNull, true); + testNumeric(null, numericValuesNull2, true); + } nullable = false; RandomData.returnNull = false; @@ -484,11 +562,14 @@ public void testNumericSpecificSetterSetObjectNull() throws SQLException { numericValuesNull2 = new String[numericValuesNull.length]; System.arraycopy(numericValuesNull, 0, numericValuesNull2, 0, numericValuesNull.length); - dropTables(stmt); - createNumericTable(); - populateNumericSetObjectNull(); - testNumeric(stmt, numericValuesNull, true); - testNumeric(null, numericValuesNull2, true); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericSetObjectNull(); + testNumeric(stmt, numericValuesNull, true); + testNumeric(null, numericValuesNull2, true); + } nullable = false; RandomData.returnNull = false; @@ -507,17 +588,23 @@ public void testNumericNormalization() throws SQLException { String[] numericValuesNormalization2 = {"true", "1", "127", "100", "100", "1.123", "1.123", "1.123", "123456789123456789", "12345.12345", "987654321123456789", "567812.78", "7812.7812", "7812.7812", "999999999999999999999999.9999", "999999999999999999999999.9999"}; - dropTables(stmt); - createNumericTable(); - populateNumericNormalCase(numericValuesNormalization); - testNumeric(stmt, numericValuesNormalization, false); - testNumeric(null, numericValuesNormalization2, false); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericNormalCase(numericValuesNormalization); + testNumeric(stmt, numericValuesNormalization, false); + testNumeric(null, numericValuesNormalization2, false); + } } private void testChar(SQLServerStatement stmt, String[] values) throws SQLException { - String sql = "select * from " + charTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(charTable); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); while (rs.next()) { @@ -526,12 +613,16 @@ 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) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(binaryTable); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); while (rs.next()) { @@ -544,9 +635,12 @@ 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) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(dateTable); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); while (rs.next()) { @@ -925,9 +1019,12 @@ 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) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (SQLServerResultSet rs = (stmt == null) ? (SQLServerResultSet) pstmt.executeQuery() : (SQLServerResultSet) stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); 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 3d1e0d354..7a343047f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigDecimal; +import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; @@ -20,10 +21,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; 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.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; /** @@ -61,101 +65,125 @@ public class PrecisionScaleTest extends AESetup { @Test public void testNumericPrecision8Scale2() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] numeric = {"1.12345", "12345.12", "567.70"}; + String[] numeric = {"1.12345", "12345.12", "567.70"}; - createNumericPrecisionTable(30, 8, 2); - populateNumericNormalCase(numeric, 8, 2); - populateNumericSetObject(numeric, 8, 2); + createNumericPrecisionTable(30, 8, 2); + populateNumericNormalCase(numeric, 8, 2); + populateNumericSetObject(numeric, 8, 2); - testNumeric(numeric); + testNumeric(numeric); + } } @Test public void testDateScale2() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateNormalCase = {GMTDate + ".18", GMTDate + ".1770000", - dateTimeOffsetExpectedValue + ".1770000 +00:01", GMTDateWithoutDate + ".1770000", - GMTDateWithoutDate + ".18", dateTimeOffsetExpectedValue + ".18 +00:01"}; - String[] dateSetObject = {GMTDate + ".18", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", - GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + ".18 +00:01"}; + String[] dateNormalCase = {GMTDate + ".18", GMTDate + ".1770000", + dateTimeOffsetExpectedValue + ".1770000 +00:01", GMTDateWithoutDate + ".1770000", + GMTDateWithoutDate + ".18", dateTimeOffsetExpectedValue + ".18 +00:01"}; + String[] dateSetObject = {GMTDate + ".18", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", + GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + ".18 +00:01"}; - createDatePrecisionTable(2); - populateDateNormalCase(2); - populateDateSetObject(2); + createDatePrecisionTable(2); + populateDateNormalCase(2); + populateDateSetObject(2); - testDate(dateNormalCase, dateSetObject); + testDate(dateNormalCase, dateSetObject); + } } @Test public void testNumericPrecision8Scale0() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] numeric2 = {"1.12345", "12345", "567"}; + String[] numeric2 = {"1.12345", "12345", "567"}; - createNumericPrecisionTable(30, 8, 0); - populateNumericNormalCase(numeric2, 8, 0); - populateNumericSetObject(numeric2, 8, 0); + createNumericPrecisionTable(30, 8, 0); + populateNumericNormalCase(numeric2, 8, 0); + populateNumericSetObject(numeric2, 8, 0); - testNumeric(numeric2); + testNumeric(numeric2); + } } @Test public void testDateScale0() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateNormalCase2 = {GMTDate, GMTDate + ".1770000", dateTimeOffsetExpectedValue + ".1770000 +00:01", - GMTDateWithoutDate + ".1770000", GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; - String[] dateSetObject2 = {GMTDate + ".0", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", - GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; + String[] dateNormalCase2 = {GMTDate, GMTDate + ".1770000", dateTimeOffsetExpectedValue + ".1770000 +00:01", + GMTDateWithoutDate + ".1770000", GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; + String[] dateSetObject2 = {GMTDate + ".0", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", + GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; - createDatePrecisionTable(0); - populateDateNormalCase(0); - populateDateSetObject(0); + createDatePrecisionTable(0); + populateDateNormalCase(0); + populateDateSetObject(0); - testDate(dateNormalCase2, dateSetObject2); + testDate(dateNormalCase2, dateSetObject2); + } } @Test public void testNumericPrecision8Scale2Null() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] numericNull = {"null", "null", "null"}; + String[] numericNull = {"null", "null", "null"}; - createNumericPrecisionTable(30, 8, 2); - populateNumericSetObjectNull(8, 2); + createNumericPrecisionTable(30, 8, 2); + populateNumericSetObjectNull(8, 2); - testNumeric(numericNull); + testNumeric(numericNull); + } } @Test public void testDateScale2Null() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; + String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; - createDatePrecisionTable(2); - populateDateSetObjectNull(2); + createDatePrecisionTable(2); + populateDateSetObjectNull(2); - testDate(dateSetObjectNull, dateSetObjectNull); + testDate(dateSetObjectNull, dateSetObjectNull); + } } @Test public void testDateScale5Null() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; + String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; - createDatePrecisionTable(5); - populateDateNormalCaseNull(5); - testDate(dateSetObjectNull, dateSetObjectNull); + createDatePrecisionTable(5); + populateDateNormalCaseNull(5); + testDate(dateSetObjectNull, dateSetObjectNull); + } } private void testNumeric(String[] numeric) throws SQLException { - try (ResultSet rs = stmt.executeQuery("select * from " + numericTable)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable))) { int numberOfColumns = rs.getMetaData().getColumnCount(); ArrayList skipMax = new ArrayList<>(); @@ -170,7 +198,9 @@ private void testNumeric(String[] numeric) throws SQLException { private void testDate(String[] dateNormalCase, String[] dateSetObject) throws Exception { - try (ResultSet rs = stmt.executeQuery("select * from " + dateTable)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(dateTable))) { int numberOfColumns = rs.getMetaData().getColumnCount(); ArrayList skipMax = new ArrayList<>(); @@ -335,11 +365,13 @@ private void testGetDate(ResultSet rs, int numberOfColumns, String[] dates) thro } private void populateDateNormalCase(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { @@ -377,11 +409,13 @@ private void populateDateNormalCase(int scale) throws SQLException { } private void populateDateNormalCaseNull(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { @@ -418,10 +452,13 @@ private void populateDateNormalCaseNull(int scale) throws SQLException { } private void populateNumericNormalCase(String[] numeric, int precision, int scale) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // float(30) for (int i = 1; i <= 3; i++) { @@ -443,10 +480,13 @@ 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( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // float(30) for (int i = 1; i <= 3; i++) { @@ -469,10 +509,13 @@ private void populateNumericSetObject(String[] numeric, int precision, int scale } private void populateNumericSetObjectNull(int precision, int scale) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // float(30) for (int i = 1; i <= 3; i++) { @@ -495,11 +538,13 @@ private void populateNumericSetObjectNull(int precision, int scale) throws SQLEx } private void populateDateSetObject(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { @@ -538,11 +583,13 @@ private void populateDateSetObject(int scale) throws SQLException { } private void populateDateSetObjectNull(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java index 369fcf7ba..bb7d317d4 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java @@ -380,38 +380,6 @@ static byte CharToHex(char value) throws SQLException { 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 * 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 6ec94f091..1a46fa823 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -61,7 +61,7 @@ public void testNoExplicitCM() { // create dest table 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); @@ -82,7 +82,7 @@ public void testExplicitCM() { // 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); @@ -120,13 +120,14 @@ public void testExplicitCM() { @DisplayName("BulkCopy:test unicode column mapping") public void testUnicodeCM() { DBTable sourceTableUnicode = null; + DBTable destTableUnicode = 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(); + destTableUnicode = sourceTableUnicode.cloneSchema(); stmt.createTable(destTableUnicode); // set up bulkCopy with explicit column mapping @@ -159,6 +160,9 @@ public void testUnicodeCM() { if (null != sourceTableUnicode) { dropTable(sourceTableUnicode.getEscapedTableName()); } + if (null != destTableUnicode) { + dropTable(destTableUnicode.getEscapedTableName()); + } } } 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 16f7d0bbc..3ce050a65 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -26,6 +26,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -43,8 +44,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 = null; - private static String desTable = null; + private static String srcTable = RandomUtil.getIdentifier("BulkCopyResultSetCursorTest_SourceTable"); + private static String desTable = RandomUtil.getIdentifier("BulkCopyResultSetCursorTest_DestinationTable"); /** * Test a previous failure when using server cursor and using the same connection to create Bulk Copy and result @@ -68,9 +69,10 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro populateSourceTable(); try (Statement stmt2 = conn.createStatement(resultSetType, resultSetConcurrency); - ResultSet rs = stmt2.executeQuery("select * from " + srcTable); + ResultSet rs = stmt2 + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { - bulkCopy.setDestinationTableName(desTable); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length); @@ -94,10 +96,10 @@ public void testSelectMethodSetToCursor() throws SQLException { createTables(stmt); populateSourceTable(); - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable); + try (ResultSet rs = stmt.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { - bulkCopy.setDestinationTableName(desTable); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length); @@ -119,28 +121,29 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { populateSourceTable(); try (Statement stmt1 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt1.executeQuery("select * from " + srcTable)) { + ResultSet rs = stmt1 + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable))) { try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { - bulkCopy.setDestinationTableName(desTable); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length); } rs.beforeFirst(); try (SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn)) { - bulkCopy1.setDestinationTableName(desTable); + bulkCopy1.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy1.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length * 2); } rs.beforeFirst(); try (SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn)) { - bulkCopy2.setDestinationTableName(desTable); + bulkCopy2.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy2.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length * 3); } - String sql = "insert into " + desTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(desTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); try (SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { for (int i = 0; i < expectedBigDecimals.length; i++) { @@ -153,9 +156,11 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { verifyDestinationTableData(expectedBigDecimals.length * 4); } try (Statement stmt2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, - ResultSet.CONCUR_UPDATABLE); ResultSet rs2 = stmt2.executeQuery("select * from " + srcTable); + ResultSet.CONCUR_UPDATABLE); + ResultSet rs2 = stmt2 + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn)) { - bulkCopy3.setDestinationTableName(desTable); + bulkCopy3.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy3.writeToServer(rs2); verifyDestinationTableData(expectedBigDecimals.length * 5); } @@ -164,8 +169,8 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { } private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); - ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + try (Connection conn = DriverManager.getConnection(connectionString); ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable))) { int expectedArrayLength = expectedBigDecimals.length; @@ -187,7 +192,7 @@ private static void verifyDestinationTableData(int expectedNumberOfRows) throws } private static void populateSourceTable() throws SQLException { - String sql = "insert into " + srcTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); try (Connection conn = DriverManager.getConnection(connectionString); @@ -205,26 +210,18 @@ private static void populateSourceTable() throws SQLException { private static void dropTables(Statement stmt) throws SQLException { if (null != srcTable) { - TestUtils.dropTableIfExists(srcTable, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); } if (null != desTable) { - TestUtils.dropTableIfExists(desTable, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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 + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); - sql = "create table " + desTable + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } 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 2b769daf0..f0a1468ea 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java @@ -9,8 +9,8 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; +import java.sql.Connection; import java.sql.DriverManager; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -22,7 +22,6 @@ import java.util.Map; import java.util.Set; -import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -30,23 +29,23 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; -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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class ISQLServerBulkRecordIssuesTest extends AbstractTest { - static Statement stmt = null; - static PreparedStatement pStmt = null; + // static Statement stmt = null; static String query; - static SQLServerConnection con = null; - static String srcTable = "sourceTable"; - static String destTable = "destTable"; + static String srcTable = RandomUtil.getIdentifier("sourceTable"); + static String destTable = RandomUtil.getIdentifier("destTable"); + String variation; /** @@ -58,20 +57,22 @@ public class ISQLServerBulkRecordIssuesTest extends AbstractTest { public void testVarchar() throws Exception { variation = "testVarchar"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (smallDATA varchar(2))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - bcOperation.close(); - fail(TestResource.getResource("R_expectedFailPassed")); - } catch (Exception e) { - if (e instanceof SQLException) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA varchar(2))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + bcOperation.close(); + fail(TestResource.getResource("R_expectedFailPassed")); + } catch (Exception e) { + if (e instanceof SQLException) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -86,16 +87,19 @@ public void testSmalldatetime() throws Exception { variation = "testSmalldatetime"; BulkData bData = new BulkData(variation); String value = ("1954-05-22 02:44:00.0").toString(); - query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - - try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { - while (rs.next()) { - assertEquals(rs.getString(1), value); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA smalldatetime)"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(destTable))) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } } } } @@ -111,22 +115,24 @@ public void testSmalldatetimeOutofRange() throws Exception { variation = "testSmalldatetimeOutofRange"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - fail("BulkCopy executed for testSmalldatetimeOutofRange when it it was expected to fail"); - } catch (Exception e) { - if (e instanceof SQLException) { - MessageFormat form = new MessageFormat(TestResource.getResource("R_conversionFailed")); - Object[] msgArgs = {"character string", "smalldatetime"}; - - assertTrue(e.getMessage().contains(form.format(msgArgs)), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA smalldatetime)"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + fail("BulkCopy executed for testSmalldatetimeOutofRange when it it was expected to fail"); + } catch (Exception e) { + if (e instanceof SQLException) { + MessageFormat form = new MessageFormat(TestResource.getResource("R_conversionFailed")); + Object[] msgArgs = {"character string", "smalldatetime"}; + + assertTrue(e.getMessage().contains(form.format(msgArgs)), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -140,19 +146,21 @@ public void testSmalldatetimeOutofRange() throws Exception { public void testBinaryColumnAsByte() throws Exception { variation = "testBinaryColumnAsByte"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (col1 binary(5))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - fail(TestResource.getResource("R_expectedFailPassed")); - } catch (Exception e) { - if (e instanceof SQLException) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + fail(TestResource.getResource("R_expectedFailPassed")); + } catch (Exception e) { + if (e instanceof SQLException) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -166,19 +174,21 @@ public void testBinaryColumnAsByte() throws Exception { public void testBinaryColumnAsString() throws Exception { variation = "testBinaryColumnAsString"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (col1 binary(5))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - fail(TestResource.getResource("R_expectedFailPassed")); - } catch (Exception e) { - if (e instanceof SQLException) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + fail(TestResource.getResource("R_expectedFailPassed")); + } catch (Exception e) { + if (e instanceof SQLException) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -192,20 +202,23 @@ public void testBinaryColumnAsString() throws Exception { public void testSendValidValueforBinaryColumnAsString() throws Exception { variation = "testSendValidValueforBinaryColumnAsString"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (col1 binary(5))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - - try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { - while (rs.next()) { - assertEquals(rs.getString(1), "0101010000"); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(destTable))) { + while (rs.next()) { + assertEquals(rs.getString(1), "0101010000"); + } } + } catch (Exception e) { + fail(e.getMessage()); } - } catch (Exception e) { - fail(e.getMessage()); } } @@ -218,10 +231,10 @@ public void testSendValidValueforBinaryColumnAsString() throws Exception { */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { - con = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = con.createStatement(); - TestUtils.dropTableIfExists(destTable, stmt); - TestUtils.dropTableIfExists(srcTable, stmt); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); + } } /** @@ -231,20 +244,11 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterEach public void afterEachTests() throws SQLException { - TestUtils.dropTableIfExists(destTable, stmt); - TestUtils.dropTableIfExists(srcTable, stmt); - } - - @AfterAll - public static void afterAllTests() throws SQLException { - if (null != stmt) { - stmt.close(); - } - if (null != con) { - con.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); } } - } 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 4c7d03c8a..e200c2e76 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java @@ -14,24 +14,30 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.junit.jupiter.api.BeforeAll; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +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 org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBPreparedStatement; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBResultSetTypes; -import com.microsoft.sqlserver.testframework.DBStatement; - @RunWith(JUnitPlatform.class) @DisplayName("BVT Test") -public class bvtTest extends bvtTestSetup { +public class bvtTest extends AbstractTest { private static String driverNamePattern = "Microsoft JDBC Driver \\d.\\d for SQL Server"; + static DBTable table1; + static DBTable table2; /** * Connect to specified server and close the connection @@ -426,4 +432,17 @@ public static void terminate() throws SQLException { + table2.getEscapedTableName()); } } + + @BeforeAll + public static void init() throws SQLException { + try (DBConnection conn = new DBConnection(connectionString); DBStatement stmt = conn.createStatement()) { + // create tables + table1 = new DBTable(true); + stmt.createTable(table1); + stmt.populateTable(table1); + table2 = new DBTable(true); + stmt.createTable(table2); + stmt.populateTable(table2); + } + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java deleted file mode 100644 index 404879fd2..000000000 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java +++ /dev/null @@ -1,41 +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.jdbc.bvt; - -import java.sql.SQLException; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBStatement; -import com.microsoft.sqlserver.testframework.DBTable; - - -/** - * - * Setting up the test - */ -@RunWith(JUnitPlatform.class) -public class bvtTestSetup extends AbstractTest { - - static DBTable table1; - static DBTable table2; - - @BeforeAll - public static void init() throws SQLException { - try (DBConnection conn = new DBConnection(connectionString); DBStatement stmt = conn.createStatement()) { - // create tables - table1 = new DBTable(true); - stmt.createTable(table1); - stmt.populateTable(table1); - table2 = new DBTable(true); - stmt.createTable(table2); - stmt.populateTable(table2); - } - } -} 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 ed0249250..fde800353 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -19,11 +19,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; /** @@ -31,13 +33,10 @@ */ @RunWith(JUnitPlatform.class) public class CallableStatementTest extends AbstractTest { - private static String tableNameGUID = "uniqueidentifier_Table"; - private static String outputProcedureNameGUID = "uniqueidentifier_SP"; - private static String setNullProcedureName = "CallableStatementTest_setNull_SP"; - private static String inputParamsProcedureName = "CallableStatementTest_inputParams_SP"; - - private static Connection connection = null; - private static Statement stmt = null; + private static String tableNameGUID = RandomUtil.getIdentifier("uniqueidentifier_Table"); + private static String outputProcedureNameGUID = RandomUtil.getIdentifier("uniqueidentifier_SP"); + private static String setNullProcedureName = RandomUtil.getIdentifier("CallableStatementTest_setNull_SP"); + private static String inputParamsProcedureName = RandomUtil.getIdentifier("CallableStatementTest_inputParams_SP"); /** * Setup before test @@ -46,18 +45,19 @@ public class CallableStatementTest extends AbstractTest { */ @BeforeAll public static void setupTest() throws SQLException { - connection = DriverManager.getConnection(connectionString); - stmt = connection.createStatement(); - - TestUtils.dropTableIfExists(tableNameGUID, stmt); - TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); - TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); - TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); - - createGUIDTable(stmt); - createGUIDStoredProcedure(stmt); - createSetNullPreocedure(stmt); - createInputParamsProcedure(stmt); + + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(setNullProcedureName), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName), stmt); + + createGUIDTable(stmt); + createGUIDStoredProcedure(stmt); + createSetNullPreocedure(stmt); + createInputParamsProcedure(stmt); + } } /** @@ -68,7 +68,7 @@ public static void setupTest() throws SQLException { @Test public void getStringGUIDTest() throws SQLException { - String sql = "{call " + outputProcedureNameGUID + "(?)}"; + String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID) + "(?)}"; try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql)) { @@ -97,7 +97,7 @@ public void getSetNullWithTypeVarchar() throws SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); ds.setSendStringParametersAsUnicode(true); - String sql = "{? = call " + setNullProcedureName + " (?,?)}"; + String sql = "{? = call " + AbstractSQLGenerator.escapeIdentifier(setNullProcedureName) + " (?,?)}"; try (Connection connection = ds.getConnection(); SQLServerCallableStatement cs = (SQLServerCallableStatement) connection.prepareCall(sql); SQLServerCallableStatement cs2 = (SQLServerCallableStatement) connection.prepareCall(sql)) { @@ -129,7 +129,7 @@ public void getSetNullWithTypeVarchar() throws SQLException { */ @Test public void inputParamsTest() throws SQLException { - String call = "{CALL " + inputParamsProcedureName + " (?,?)}"; + String call = "{CALL " + AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName) + " (?,?)}"; // the historical way: no leading '@', parameter names respected (not positional) try (CallableStatement cs = connection.prepareCall(call)) { @@ -173,39 +173,39 @@ public void inputParamsTest() throws SQLException { */ @AfterAll public static void cleanup() throws SQLException { - TestUtils.dropTableIfExists(tableNameGUID, stmt); - TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); - TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); - TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { - if (null != stmt) { - stmt.close(); - } - if (null != connection) { - connection.close(); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(setNullProcedureName), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName), stmt); } } private static void createGUIDStoredProcedure(Statement stmt) throws SQLException { - String sql = "CREATE PROCEDURE " + outputProcedureNameGUID - + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " + tableNameGUID + ";"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID) + + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableNameGUID) + ";"; stmt.execute(sql); } private static void createGUIDTable(Statement stmt) throws SQLException { - String sql = "CREATE TABLE " + tableNameGUID + " (c1 uniqueidentifier null)"; + String sql = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableNameGUID) + + " (c1 uniqueidentifier null)"; stmt.execute(sql); } private static void createSetNullPreocedure(Statement stmt) throws SQLException { - stmt.execute("create procedure " + setNullProcedureName + stmt.execute("create procedure " + AbstractSQLGenerator.escapeIdentifier(setNullProcedureName) + " (@p1 nvarchar(255), @p2 nvarchar(255) output) as select @p2=@p1 return 0"); } private static void createInputParamsProcedure(Statement stmt) throws SQLException { - String sql = "CREATE PROCEDURE [dbo].[CallableStatementTest_inputParams_SP] " + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName) + " @p1 nvarchar(max) = N'parameter1', " + " @p2 nvarchar(max) = N'parameter2' " + "AS " + "BEGIN " + " SET NOCOUNT ON; " + " SELECT @p1 + @p2 AS result; " + "END "; + stmt.execute(sql); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java index 24b12f18e..79040c3e1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -40,14 +40,13 @@ import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.SQLServerDriver; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBTable; - @RunWith(JUnitPlatform.class) public class ConnectionDriverTest extends AbstractTest { - // If no retry is done, the function should atleast exit in 5 seconds + // If no retry is done, the function should at least exit in 5 seconds static int threshHoldForNoRetryInMilliseconds = 5000; static int loginTimeOutInSeconds = 10; @@ -307,23 +306,24 @@ public void testDeadConnection() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), TestResource.getResource("R_skipAzure")); - String tableName = null; + String tableName = RandomUtil.getIdentifier("ConnectionTestTable"); try (SQLServerConnection conn = (SQLServerConnection) DriverManager .getConnection(connectionString + ";responseBuffering=adaptive"); Statement stmt = conn.createStatement()) { - tableName = RandomUtil.getIdentifier("Table"); - tableName = DBTable.escapeIdentifier(tableName); - conn.setAutoCommit(false); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); + stmt.executeUpdate( + "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int primary key)"); for (int i = 0; i < 80; i++) { - stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(col1) values (" + + i + ")"); } conn.commit(); try { - stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " - + tableName + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); + stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " as x1, " + + AbstractSQLGenerator.escapeIdentifier(tableName) + + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); } catch (SQLException e) { assertEquals(e.getMessage(), TestResource.getResource("R_connectionReset"), TestResource.getResource("R_unknownException")); @@ -336,7 +336,7 @@ public void testDeadConnection() throws SQLException { try (SQLServerConnection conn = (SQLServerConnection) DriverManager .getConnection(connectionString + ";responseBuffering=adaptive"); Statement stmt = conn.createStatement()) { - stmt.execute("drop table " + tableName); + stmt.execute("drop table " + AbstractSQLGenerator.escapeIdentifier(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 307c9a0c1..9408f7d3d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -23,6 +23,7 @@ import javax.sql.PooledConnection; import org.apache.commons.dbcp2.BasicDataSource; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -32,9 +33,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerXADataSource; 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.DBTable; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; @@ -45,16 +46,14 @@ */ @RunWith(JUnitPlatform.class) public class PoolingTest extends AbstractTest { + static String tempTableName = RandomUtil.getIdentifier("#poolingtest"); + static String tableName = RandomUtil.getIdentifier("PoolingTestTable"); + @Test public void testPooling() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), "Skipping test case on Azure SQL."); - String randomTableName = RandomUtil.getIdentifier("table"); - - // make the table a temporary table (will be created in tempdb database) - String tempTableName = "#" + randomTableName; - SQLServerXADataSource XADataSource1 = new SQLServerXADataSource(); XADataSource1.setURL(connectionString); XADataSource1.setDatabaseName("tempdb"); @@ -63,8 +62,8 @@ public void testPooling() throws SQLException { try (Connection conn = pc.getConnection(); Statement stmt = conn.createStatement()) { // create table in tempdb database - stmt.execute("create table [" + tempTableName + "] (myid int)"); - stmt.execute("insert into [" + tempTableName + "] values (1)"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tempTableName) + " (myid int)"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(tempTableName) + " values (1)"); } boolean tempTableFileRemoved = false; @@ -100,14 +99,12 @@ public void testConnectionPoolReget() throws SQLException { @Test public void testConnectionPoolConnFunctions() throws SQLException { - String tableName = RandomUtil.getIdentifier("table"); - tableName = DBTable.escapeIdentifier(tableName); - String sql1 = "if exists (select * from dbo.sysobjects where name = '" + TestUtils.escapeSingleQuotes(tableName) - + "' and type = 'U')\n" + "drop table " + tableName + "\n" + "create table " + tableName + "\n" + "(\n" + + "' and type = 'U')\n" + "drop table " + AbstractSQLGenerator.escapeIdentifier(tableName) + "\n" + + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + "\n" + "(\n" + "wibble_id int primary key not null,\n" + "counter int null\n" + ");"; String sql2 = "if exists (select * from dbo.sysobjects where name = '" + TestUtils.escapeSingleQuotes(tableName) - + "' and type = 'U')\n" + "drop table " + tableName + "\n"; + + "' and type = 'U')\n" + "drop table " + AbstractSQLGenerator.escapeIdentifier(tableName) + "\n"; SQLServerXADataSource ds = new SQLServerXADataSource(); ds.setURL(connectionString); @@ -252,4 +249,17 @@ private static int countTimeoutThreads() { return count; } + + /** + * drop the tables + * + * @throws SQLException + */ + @AfterAll + public static void afterAll() throws SQLException { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tempTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + } + } } 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 2882437a9..4e8eeaaec 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -39,6 +39,8 @@ @RunWith(JUnitPlatform.class) public class RequestBoundaryMethodsTest extends AbstractTest { + static String tableName = RandomUtil.getIdentifier("RequestBoundaryTable"); + /** * Tests Request Boundary methods with SQLServerConnection properties that are modifiable through public APIs. * @@ -174,25 +176,23 @@ public void testWarnings() throws SQLException { */ @Test public void testOpenTransactions() throws SQLException { - String tableName = null; - try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { if (TestUtils.isJDBC43OrGreater(con)) { - tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundaryTable")); - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col int)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col int)"); con.beginRequest(); con.setAutoCommit(false); - stmt.executeUpdate("INSERT INTO " + tableName + " values(5)"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(5)"); // endRequest() does a rollback here, the value does not get inserted into the table. con.endRequest(); con.commit(); - try (ResultSet rs = con.createStatement().executeQuery("SELECT * from " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { assertTrue(!rs.isBeforeFirst(), "Should not have returned a result set."); } finally { if (null != tableName) { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -209,8 +209,6 @@ public void testOpenTransactions() throws SQLException { @SuppressWarnings("resource") @Test public void testStatements() throws SQLException { - String tableName = null; - try (SQLServerConnection con = connect();) { if (TestUtils.isJDBC43OrGreater(con)) { try (Statement stmt1 = con.createStatement()) { @@ -233,18 +231,19 @@ public void testStatements() throws SQLException { // Multiple statements inside beginRequest()/endRequest() block con.beginRequest(); 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 (?)")) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col int)"); + try (PreparedStatement ps = con.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?)")) { ps.setInt(1, 2); ps.executeUpdate(); - try (Statement stmt1 = con.createStatement(); - ResultSet rs = stmt1.executeQuery("SELECT * FROM " + tableName)) { + try (Statement stmt1 = con.createStatement(); ResultSet rs = stmt1 + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); assertEquals(2, rs.getInt(1)); - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); try (CallableStatement cs = con.prepareCall("{call sp_server_info}")) { cs.execute(); @@ -261,7 +260,7 @@ public void testStatements() throws SQLException { } finally { if (null != tableName) { try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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 7cf40cc43..61a17bea6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java @@ -13,6 +13,7 @@ import java.sql.SQLException; import java.sql.Statement; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; @@ -23,13 +24,14 @@ 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; @RunWith(JUnitPlatform.class) public class TimeoutTest extends AbstractTest { String randomServer = RandomUtil.getIdentifier("Server"); - String waitForDelaySPName = "waitForDelaySP"; + static String waitForDelaySPName = RandomUtil.getIdentifier("waitForDelaySP"); final int waitForDelaySeconds = 10; @Test @@ -98,7 +100,6 @@ public void testFOInstanceResolution2() throws SQLException { @Test public void testQueryTimeout() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -107,7 +108,7 @@ public void testQueryTimeout() throws Exception { .getConnection(connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";")) { try (Statement stmt = conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { @@ -136,7 +137,6 @@ public void testQueryTimeout() throws Exception { public void testCancelQueryTimeout() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -145,7 +145,7 @@ public void testCancelQueryTimeout() throws Exception { + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + ";")) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { @@ -173,7 +173,6 @@ public void testCancelQueryTimeout() throws Exception { @Test public void testCancelQueryTimeoutOnStatement() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -183,7 +182,7 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.setQueryTimeout(waitForDelaySeconds / 2); stmt.setCancelQueryTimeout(waitForDelaySeconds); - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { @@ -211,7 +210,6 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { @Test public void testSocketTimeout() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -220,7 +218,7 @@ public void testSocketTimeout() throws Exception { .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";")) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof SQLException)) { @@ -241,9 +239,9 @@ public void testSocketTimeout() throws Exception { } } - private void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLException { + private static void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLException { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - TestUtils.dropProcedureIfExists(waitForDelaySPName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } @@ -251,12 +249,18 @@ private void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLExcep private void createWaitForDelayPreocedure(SQLServerConnection conn) throws SQLException { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - - String sql = "CREATE PROCEDURE " + waitForDelaySPName + " AS" + " BEGIN" + " WAITFOR DELAY '00:00:" - + waitForDelaySeconds + "';" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName) + " AS" + + " BEGIN" + " WAITFOR DELAY '00:00:" + waitForDelaySeconds + "';" + " END"; stmt.execute(sql); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } } + + @AfterAll + public static void cleanup() throws SQLException { + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + dropWaitForDelayProcedure(conn); + } + } } 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 119656188..ffd34ad73 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java @@ -18,12 +18,14 @@ 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.SQLServerDatabaseMetaData; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -32,13 +34,12 @@ */ @RunWith(JUnitPlatform.class) public class DatabaseMetaDataForeignKeyTest extends AbstractTest { - private static SQLServerConnection conn = null; - private static String table1 = "DatabaseMetaDataForeignKeyTest_table_1"; - private static String table2 = "DatabaseMetaDataForeignKeyTest_table_2"; - private static String table3 = "DatabaseMetaDataForeignKeyTest_table_3"; - private static String table4 = "DatabaseMetaDataForeignKeyTest_table_4"; - private static String table5 = "DatabaseMetaDataForeignKeyTest_table_5"; + private static String table1 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_1"); + private static String table2 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_2"); + private static String table3 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_3"); + private static String table4 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_4"); + private static String table5 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_5"); private static String schema = null; private static String catalog = null; @@ -50,23 +51,38 @@ public static void setupVariation() throws SQLException { 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," + ")"); + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table1) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table1)); + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table2) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table2)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table2) + + " (c21 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table3) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table3)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table3) + + " (c31 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table4) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table4)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table4) + + " (c41 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table5) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table5)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table5) + + " (c51 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table1) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table1)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table1) + " (c11 int primary key," + + " c12 int FOREIGN KEY REFERENCES " + AbstractSQLGenerator.escapeIdentifier(table2) + + "(c21) ON DELETE no action ON UPDATE set default," + " c13 int FOREIGN KEY REFERENCES " + + AbstractSQLGenerator.escapeIdentifier(table3) + "(c31) ON DELETE cascade ON UPDATE set null," + + " c14 int FOREIGN KEY REFERENCES " + AbstractSQLGenerator.escapeIdentifier(table4) + + "(c41) ON DELETE set null ON UPDATE cascade," + " c15 int FOREIGN KEY REFERENCES " + + AbstractSQLGenerator.escapeIdentifier(table5) + "(c51) ON DELETE set default ON UPDATE no action," + + ")"); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } @@ -77,11 +93,11 @@ public static void terminateVariation() throws SQLException { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - TestUtils.dropTableIfExists(table1, stmt); - TestUtils.dropTableIfExists(table2, stmt); - TestUtils.dropTableIfExists(table3, stmt); - TestUtils.dropTableIfExists(table4, stmt); - TestUtils.dropTableIfExists(table5, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table3), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table4), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table5), 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 f09323fa3..681462715 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java @@ -19,9 +19,11 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -32,8 +34,8 @@ @RunWith(JUnitPlatform.class) public class BulkCopyWithSqlVariantTest extends AbstractTest { - static String tableName = "sqlVariantTestSrcTable"; - static String destTableName = "sqlVariantDestTable"; + static String tableName = RandomUtil.getIdentifier("sqlVariantTestSrcTable"); + static String destTableName = RandomUtil.getIdentifier("dest_sqlVariant"); /** * Test integer value @@ -47,14 +49,16 @@ public void bulkCopyTestInt() throws SQLException { int col1Value = 5; beforeEachSetup("int", col1Value); try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getInt(1), 5); } @@ -78,13 +82,15 @@ public void bulkCopyTestSmallInt() throws SQLException { try (Statement stmt = con.createStatement()) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getShort(1), 5); } @@ -109,13 +115,15 @@ public void bulkCopyTestTinyint() throws SQLException { try (Statement stmt = con.createStatement()) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getByte(1), 5); } @@ -138,14 +146,16 @@ public void bulkCopyTestBigint() throws SQLException { beforeEachSetup("bigint", col1Value); try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getLong(1), col1Value); } @@ -169,15 +179,17 @@ public void bulkCopyTestFloat() throws SQLException { try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getDouble(1), col1Value); } @@ -200,15 +212,17 @@ public void bulkCopyTestReal() throws SQLException { try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getFloat(1), col1Value); } @@ -231,14 +245,16 @@ public void bulkCopyTestMoney() throws SQLException { try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getMoney(1), new BigDecimal(col1Value)); } @@ -257,23 +273,26 @@ public void bulkCopyTestSmallmoney() throws SQLException { 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)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values (CAST (" + col1Value + " AS " + "smallmoney" + ") )"); stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "smallmoney" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + "create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + " (col1 sql_variant)"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getSmallMoney(1), new BigDecimal(col1Value)); } @@ -293,15 +312,17 @@ public void bulkCopyTestDate() throws SQLException { String col1Value = "2015-05-05"; beforeEachSetup("date", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getDate(1), col1Value); } @@ -320,23 +341,27 @@ 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)"); - - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1, col2) values (CAST ('" + col1Value + "' AS " + "date" + ")" + ",CAST (" + col2Value + + " AS " + "smallmoney" + ") )"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + + " (col1 sql_variant, col2 sql_variant)"); + + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getDate(1), col1Value); assertEquals(rs.getSmallMoney(2), new BigDecimal(col2Value)); @@ -356,14 +381,16 @@ public void bulkCopyTestTimeWithScale() throws SQLException { String col1Value = "'12:26:27.1452367'"; beforeEachSetup("time(2)", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getString(1), "12:26:27.15"); // getTime does not work } @@ -384,14 +411,16 @@ public void bulkCopyTestChar() throws SQLException { beforeEachSetup("char", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getString(1).trim() + "'", col1Value); // adds space between } @@ -411,14 +440,16 @@ public void bulkCopyTestNchar() throws SQLException { String col1Value = "'a'"; beforeEachSetup("nchar", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getNString(1).trim() + "'", col1Value); } @@ -439,14 +470,16 @@ public void bulkCopyTestVarchar() throws SQLException { beforeEachSetup("varchar", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getString(1).trim() + "'", col1Value); } @@ -466,14 +499,16 @@ public void bulkCopyTestNvarchar() throws SQLException { String col1Value = "'hello'"; beforeEachSetup("nvarchar", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getString(1).trim() + "'", col1Value); } @@ -493,15 +528,17 @@ public void bulkCopyTestBinary20() throws SQLException { String col1Value = "hello"; beforeEachSetup("binary(20)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } @@ -521,15 +558,17 @@ public void bulkCopyTestVarbinary20() throws SQLException { String col1Value = "hello"; beforeEachSetup("varbinary(20)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } @@ -548,14 +587,16 @@ public void bulkCopyTestVarbinary8000() throws SQLException { String col1Value = "hello"; beforeEachSetup("binary(8000)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } @@ -574,15 +615,17 @@ public void bulkCopyTestBitNull() throws SQLException { beforeEachSetup("bit", null); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getBoolean(1), false); } @@ -601,15 +644,17 @@ public void bulkCopyTestBit() throws SQLException { int col1Value = 5000; beforeEachSetup("bit", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getBoolean(1), true); } @@ -629,15 +674,17 @@ public void bulkCopyTestDatetime() throws SQLException { String col1Value = "2015-05-08 12:26:24.0"; beforeEachSetup("datetime", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getDateTime(1), col1Value); @@ -658,15 +705,17 @@ public void bulkCopyTestSmalldatetime() throws SQLException { String col1Value = "2015-05-08 12:26:24"; beforeEachSetup("smalldatetime", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getSmallDateTime(1), "2015-05-08 12:26:00.0"); } @@ -686,15 +735,17 @@ public void bulkCopyTestDatetime2() throws SQLException { String col1Value = "2015-05-08 12:26:24.12645"; beforeEachSetup("datetime2(2)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getTimestamp(1), "2015-05-08 12:26:24.13"); } @@ -712,22 +763,25 @@ public void bulkCopyTestTime() throws SQLException { 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)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values (CAST (" + col1Value + " AS " + "time(2)" + ") )"); stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "time(2)" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + "create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + " (col1 sql_variant)"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { rs.next(); assertEquals("" + rs.getObject(1).toString(), "12:26:27"); } @@ -745,15 +799,17 @@ public void bulkCopyTestReadGUID() throws SQLException { String col1Value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; beforeEachSetup("uniqueidentifier", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getUniqueIdentifier(1), col1Value); @@ -778,15 +834,17 @@ public void bulkCopyTestVarChar8000() throws SQLException { String col1Value = buffer.toString(); beforeEachSetup("varchar(8000)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getString(1), col1Value); } @@ -797,12 +855,14 @@ public void bulkCopyTestVarChar8000() throws SQLException { private void beforeEachSetup(String colType, Object colValue) throws SQLException { 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)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values (CAST (" + colValue + " AS " + colType + ") )"); stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + colValue + " AS " + colType + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + "create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + " (col1 sql_variant)"); } } @@ -815,7 +875,7 @@ private void beforeEachSetup(String colType, Object colValue) throws SQLExceptio public static void afterAll() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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 92b22d357..16daac876 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java @@ -24,10 +24,12 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; @@ -39,6 +41,11 @@ 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); + private String dateTVP = RandomUtil.getIdentifier("dateTVP"); + private String timeTVP = RandomUtil.getIdentifier("timeTVP"); + private String timestampTVP = RandomUtil.getIdentifier("timestampTVP"); + private static String tableName = RandomUtil.getIdentifier("DataTypesTable"); + /** * Test query with date */ @@ -46,7 +53,8 @@ public class DateAndTimeTypeTest extends AbstractTest { public void testQueryDate() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { - String sPrepStmt = "select * from dateandtime where my_date = ?"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_date = ?"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setDate(1, DATE_TO_TEST); @@ -65,7 +73,8 @@ public void testQueryDate() throws SQLException { public void testQueryTimestamp() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { - String sPrepStmt = "select * from dateandtime where my_timestamp = ?"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_timestamp = ?"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setTimestamp(1, TIMESTAMP_TO_TEST); @@ -84,7 +93,8 @@ public void testQueryTimestamp() throws SQLException { public void testQueryTime() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { - String sPrepStmt = "select * from dateandtime where my_time = ?"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_time = ?"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setTime(1, TIME_TO_TEST); @@ -106,10 +116,11 @@ 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 ?)"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_date IN (select * from ?)"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection .prepareStatement(sPrepStmt)) { - pstmt.setStructured(1, "dateTVP", tvp); + pstmt.setStructured(1, dateTVP, tvp); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); @@ -129,10 +140,11 @@ 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 ?)"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_timestamp IN (select * from ?)"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection .prepareStatement(sPrepStmt)) { - pstmt.setStructured(1, "timestampTVP", tvp); + pstmt.setStructured(1, timestampTVP, tvp); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); @@ -152,10 +164,11 @@ 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 ?)"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_time IN (select * from ?)"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection .prepareStatement(sPrepStmt)) { - ((SQLServerPreparedStatement) pstmt).setStructured(1, "timeTVP", tvp); + ((SQLServerPreparedStatement) pstmt).setStructured(1, timeTVP, tvp); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); @@ -169,9 +182,11 @@ private void createTVPs(String tvpName, String tvpType) throws SQLException { 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("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 " + + tvpType + " null)"; stmt.executeUpdate(TVPCreateCmd); } } @@ -186,12 +201,14 @@ public void testSetup() throws TestAbortedException, Exception { // by default to the connection. See issue https://github.com/Microsoft/mssql-jdbc/issues/559 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))"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (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 (?, ?, ?, ?)"; + String sPrepStmt = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id, my_date, my_time, my_timestamp) values (?, ?, ?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setInt(1, 42); pstmt.setDate(2, DATE_TO_TEST); @@ -199,9 +216,9 @@ public void testSetup() throws TestAbortedException, Exception { pstmt.setTimestamp(4, TIMESTAMP_TO_TEST); pstmt.execute(); pstmt.close(); - createTVPs("dateTVP", "date"); - createTVPs("timeTVP", "time"); - createTVPs("timestampTVP", "datetime2"); + createTVPs(dateTVP, "date"); + createTVPs(timeTVP, "time"); + createTVPs(timestampTVP, "datetime2"); } } } @@ -210,7 +227,7 @@ public void testSetup() throws TestAbortedException, Exception { public static void terminateVariation() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists("dateandtime", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), 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 bd4e24db8..6a95f29c9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java @@ -25,12 +25,14 @@ import com.microsoft.sqlserver.jdbc.Geography; import com.microsoft.sqlserver.jdbc.Geometry; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -41,9 +43,9 @@ @RunWith(JUnitPlatform.class) public class SQLServerSpatialDatatypeTest extends AbstractTest { - static String geomTableName = "geometryTestTable"; - static String geogTableName = "geographyTestTable"; - static String spatialDatatypeTableName = "spatialDatatypeTestTable"; + static String geomTableName; + static String geogTableName; + static String spatialDatatypeTableName; static boolean isDenaliOrLater = false; @Test @@ -315,13 +317,13 @@ public void testFullGlobeWkt() throws SQLException { assertEquals(e.getMessage(), "Fullglobe is not supported for Geometry."); } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKT); } @@ -479,8 +481,8 @@ public void testAllTypes() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)")) { geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); pstmt.setGeometry(1, geomWKT); pstmt.executeUpdate(); @@ -522,7 +524,7 @@ public void testAllTypes() throws SQLException { pstmt.executeUpdate(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); @@ -531,8 +533,8 @@ public void testAllTypes() throws SQLException { } // Geography - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)")) { geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); pstmt.setGeography(1, geogWKT); @@ -584,7 +586,7 @@ public void testAllTypes() throws SQLException { pstmt.executeUpdate(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKTList.get(i)); @@ -633,8 +635,9 @@ public void testMixedAllTypes() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) + + " values (?, ?, ?, ?, ?)");) { geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); pstmt.setGeometry(1, geomWKT); @@ -735,8 +738,8 @@ public void testMixedAllTypes() throws SQLException { pstmt.executeUpdate(); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select * from " + spatialDatatypeTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); @@ -773,26 +776,26 @@ public void testParse() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); assertEquals(rs.getGeometry(1).getSrid(), 0); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKT); assertEquals(rs.getGeography(1).getSrid(), 4326); @@ -814,26 +817,26 @@ public void testPoint() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); assertEquals(rs.getGeometry(1).getSrid(), 0); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKT); assertEquals(rs.getGeography(1).getSrid(), 4326); @@ -855,25 +858,25 @@ public void testSTAsText() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).STAsText(), geoWKTSS); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).STAsText(), geoWKTSS); } @@ -909,8 +912,8 @@ public void testCheckGeomMetaData() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + geomTableName + " (c1) VALUES (?)")) { + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); Geometry g = Geometry.STGeomFromText("POINT (1 2 3 4)", 0); pstmt.setGeometry(1, g); @@ -920,7 +923,8 @@ public void testCheckGeomMetaData() throws SQLException { String sqlTypeName = paramMetaData.getParameterTypeName(1); assertEquals(sqlType, -157); assertEquals(sqlTypeName, "geometry"); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geomTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { ResultSetMetaData rsmd = rs.getMetaData(); assertEquals(rsmd.getColumnType(1), -157); } @@ -933,8 +937,8 @@ public void testCheckGeogMetaData() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + geogTableName + " (c1) VALUES (?)")) { + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); Geography g = Geography.STGeomFromText("POINT (1 2 3 4)", 4326); pstmt.setGeography(1, g); @@ -944,7 +948,8 @@ public void testCheckGeogMetaData() throws SQLException { String sqlTypeName = paramMetaData.getParameterTypeName(1); assertEquals(sqlType, -158); assertEquals(sqlTypeName, "geography"); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geogTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { ResultSetMetaData rsmd = rs.getMetaData(); assertEquals(rsmd.getColumnType(1), -158); } @@ -998,8 +1003,9 @@ public void testNull() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) + + " values (?, ?, ?, ?, ?)");) { geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); pstmt.setGeometry(1, geomWKT); @@ -1020,8 +1026,8 @@ public void testNull() throws SQLException { pstmt.executeUpdate(); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select * from " + spatialDatatypeTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTListExpected.get(i)); @@ -1039,19 +1045,21 @@ public void testNull() throws SQLException { private void beforeEachSetup() throws SQLException { 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)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geomTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geogTableName), stmt); + stmt.executeUpdate( + "Create table " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " (c1 geometry)"); + stmt.executeUpdate( + "Create table " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " (c1 geography)"); } } private void beforeEachSetupSpatialDatatype() throws SQLException { 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)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName), stmt); + stmt.executeUpdate("Create table " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) + + " (c1 geometry," + "c2 geography," + "c3 nvarchar(512)," + "c4 decimal(28,4)," + "c5 int)"); } } @@ -1066,25 +1074,25 @@ private void testWkt(String geoWKT, String geoWKTSS) throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTSS); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKTSS); } @@ -1111,6 +1119,10 @@ private static byte[] hexStringToByteArray(String s) { */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { + geomTableName = RandomUtil.getIdentifier("geometryTestTable"); + geogTableName = RandomUtil.getIdentifier("geographyTestTable"); + spatialDatatypeTableName = RandomUtil.getIdentifier("spatialDatatypeTestTable"); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt .executeQuery("select SERVERPROPERTY ( 'ProductVersion' )")) { @@ -1139,8 +1151,9 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti 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); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geomTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geogTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName), stmt); } } } 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 cfb5729b4..babee66d8 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java @@ -24,12 +24,14 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -40,12 +42,8 @@ @RunWith(JUnitPlatform.class) public class SQLVariantResultSetTest extends AbstractTest { - static SQLServerConnection con = null; - static Statement stmt = null; - static String tableName = "sqlVariantTestSrcTable"; - static String inputProc = "sqlVariantProc"; - static SQLServerResultSet rs = null; - static SQLServerPreparedStatement pstmt = null; + static String tableName; + static String inputProc; /** * Read int value @@ -56,11 +54,17 @@ public class SQLVariantResultSetTest extends AbstractTest { */ @Test public void readInt() throws SQLException, SecurityException, IOException { - int value = 2; - createAndPopulateTable("int", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + + int value = 2; + createAndPopulateTable("int", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + value); + } + } } /** @@ -71,11 +75,16 @@ public void readInt() throws SQLException, SecurityException, IOException { */ @Test public void readMoney() throws SQLException { - Double value = 123.12; - createAndPopulateTable("Money", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + Double value = 123.12; + createAndPopulateTable("Money", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + } + } } /** @@ -85,11 +94,16 @@ public void readMoney() throws SQLException { */ @Test public void readSmallMoney() throws SQLException { - Double value = 123.12; - createAndPopulateTable("smallmoney", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + Double value = 123.12; + createAndPopulateTable("smallmoney", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + } + } } /** @@ -99,11 +113,16 @@ public void readSmallMoney() throws SQLException { */ @Test public void readGUID() throws SQLException { - String value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; - createAndPopulateTable("uniqueidentifier", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getUniqueIdentifier(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; + createAndPopulateTable("uniqueidentifier", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getUniqueIdentifier(1), value); + } + } } /** @@ -113,11 +132,16 @@ public void readGUID() throws SQLException { */ @Test public void readDate() throws SQLException { - String value = "'2015-05-08'"; - createAndPopulateTable("date", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1), "2015-05-08"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'2015-05-08'"; + createAndPopulateTable("date", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1), "2015-05-08"); + } + } } /** @@ -127,11 +151,16 @@ public void readDate() throws SQLException { */ @Test public void readTime() throws SQLException { - String value = "'12:26:27.123345'"; - createAndPopulateTable("time(3)", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1).toString(), "12:26:27"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'12:26:27.123345'"; + createAndPopulateTable("time(3)", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1).toString(), "12:26:27"); + } + } } /** @@ -141,11 +170,16 @@ public void readTime() throws SQLException { */ @Test public void readDateTime() throws SQLException { - String value = "'2015-05-08 12:26:24'"; - createAndPopulateTable("datetime", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1), "2015-05-08 12:26:24.0"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'2015-05-08 12:26:24'"; + createAndPopulateTable("datetime", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1), "2015-05-08 12:26:24.0"); + } + } } /** @@ -155,11 +189,16 @@ public void readDateTime() throws SQLException { */ @Test public void readSmallDateTime() throws SQLException { - String value = "'2015-05-08 12:26:24'"; - createAndPopulateTable("smalldatetime", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1), "2015-05-08 12:26:00.0"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'2015-05-08 12:26:24'"; + createAndPopulateTable("smalldatetime", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1), "2015-05-08 12:26:00.0"); + } + } } /** @@ -175,9 +214,12 @@ public void readVarChar8000() throws SQLException { } String value = "'" + buffer.toString() + "'"; createAndPopulateTable("VARCHAR(8000)", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), buffer.toString()); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), buffer.toString()); + } } /** @@ -187,11 +229,16 @@ public void readVarChar8000() throws SQLException { */ @Test public void readFloat() throws SQLException { - float value = 5; - createAndPopulateTable("float", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), Double.valueOf("5.0")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + float value = 5; + createAndPopulateTable("float", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), Double.valueOf("5.0")); + } + } } /** @@ -201,11 +248,16 @@ public void readFloat() throws SQLException { */ @Test public void readBigInt() throws SQLException { - long value = 5; - createAndPopulateTable("bigint", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + long value = 5; + createAndPopulateTable("bigint", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -215,11 +267,16 @@ public void readBigInt() throws SQLException { */ @Test public void readSmallInt() throws SQLException { - short value = 5; - createAndPopulateTable("smallint", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + short value = 5; + createAndPopulateTable("smallint", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -229,11 +286,16 @@ public void readSmallInt() throws SQLException { */ @Test public void readTinyInt() throws SQLException { - short value = 5; - createAndPopulateTable("tinyint", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + short value = 5; + createAndPopulateTable("tinyint", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -243,11 +305,16 @@ public void readTinyInt() throws SQLException { */ @Test public void readBit() throws SQLException { - int value = 50000; - createAndPopulateTable("bit", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), true); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int value = 50000; + createAndPopulateTable("bit", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), true); + } + } } /** @@ -257,11 +324,16 @@ public void readBit() throws SQLException { */ @Test public void readReal() throws SQLException { - float value = 5; - createAndPopulateTable("Real", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), Float.valueOf("5.0")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + float value = 5; + createAndPopulateTable("Real", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), Float.valueOf("5.0")); + } + } } /** @@ -271,11 +343,16 @@ public void readReal() throws SQLException { */ @Test public void readNChar() throws SQLException, SecurityException, IOException { - String value = "a"; - createAndPopulateTable("nchar(5)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getNString(1).trim(), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "a"; + createAndPopulateTable("nchar(5)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getNString(1).trim(), value); + } + } } /** @@ -287,11 +364,16 @@ public void readNChar() throws SQLException, SecurityException, IOException { */ @Test public void readNVarChar() throws SQLException, SecurityException, IOException { - String value = "nvarchar"; - createAndPopulateTable("nvarchar(10)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "nvarchar"; + createAndPopulateTable("nvarchar(10)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -303,11 +385,16 @@ public void readNVarChar() throws SQLException, SecurityException, IOException { */ @Test public void readBinary20() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(20)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(20)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -319,11 +406,16 @@ public void readBinary20() throws SQLException, SecurityException, IOException { */ @Test public void readVarBinary20() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("varbinary(20)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("varbinary(20)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -335,11 +427,16 @@ public void readVarBinary20() throws SQLException, SecurityException, IOExceptio */ @Test public void readBinary512() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(512)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(512)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -351,11 +448,16 @@ public void readBinary512() throws SQLException, SecurityException, IOException */ @Test public void readBinary8000() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(8000)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(8000)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -367,11 +469,16 @@ public void readBinary8000() throws SQLException, SecurityException, IOException */ @Test public void readvarBinary8000() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("varbinary(8000)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("varbinary(8000)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -383,14 +490,18 @@ public void readvarBinary8000() throws SQLException, SecurityException, IOExcept */ @Test public void readSQLVariantProperty() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(8000)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery( - "SELECT SQL_VARIANT_PROPERTY(col1,'BaseType') AS 'Base Type', SQL_VARIANT_PROPERTY(col1,'Precision') AS 'Precision' from " - + tableName); - rs.next(); - assertTrue(rs.getString(1).equalsIgnoreCase("binary"), - "unexpected baseType, expected: binary, retrieved:" + rs.getString(1)); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(8000)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "SELECT SQL_VARIANT_PROPERTY(col1,'BaseType') AS 'Base Type', SQL_VARIANT_PROPERTY(col1,'Precision') AS 'Precision' from " + + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(rs.getString(1).equalsIgnoreCase("binary"), + "unexpected baseType, expected: binary, retrieved:" + rs.getString(1)); + } + } } /** @@ -404,15 +515,20 @@ public void insertVarChar8001() throws SQLException { for (int i = 0; i < 8001; i++) { buffer.append("a"); } - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + tableName + " values (?)"); - pstmt.setObject(1, buffer.toString()); - try { - pstmt.execute(); - } catch (SQLServerException e) { - assertTrue(e.toString().contains("com.microsoft.sqlserver.jdbc.SQLServerException: Operand type clash")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?)"); + pstmt.setObject(1, buffer.toString()); + try { + pstmt.execute(); + } catch (SQLServerException e) { + assertTrue( + e.toString().contains("com.microsoft.sqlserver.jdbc.SQLServerException: Operand type clash")); + } } } @@ -429,9 +545,14 @@ public void readNvarChar4000() throws SQLException { } String value = "'" + buffer.toString() + "'"; createAndPopulateTable("NVARCHAR(4000)", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), buffer.toString()); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), buffer.toString()); + } + } } /** @@ -443,20 +564,23 @@ public void readNvarChar4000() throws SQLException { */ @Test public void UpdateInt() throws SQLException, SecurityException, IOException { - int value = 2; - int updatedValue = 3; - createAndPopulateTable("int", value); - stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + value); - rs.updateInt(1, updatedValue); - rs.updateRow(); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + updatedValue); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + int value = 2; + int updatedValue = 3; + createAndPopulateTable("int", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + value); + rs.updateInt(1, updatedValue); + rs.updateRow(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + updatedValue); + } } } @@ -469,21 +593,25 @@ public void UpdateInt() throws SQLException, SecurityException, IOException { */ @Test public void UpdateNChar() throws SQLException, SecurityException, IOException { - String value = "a"; - String updatedValue = "b"; - - createAndPopulateTable("nchar", "'" + value + "'"); - stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1).trim(), "" + value); - rs.updateNString(1, updatedValue); - rs.updateRow(); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + updatedValue); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + String value = "a"; + String updatedValue = "b"; + + createAndPopulateTable("nchar", "'" + value + "'"); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1).trim(), "" + value); + rs.updateNString(1, updatedValue); + rs.updateRow(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + updatedValue); + } } } @@ -496,20 +624,24 @@ public void UpdateNChar() throws SQLException, SecurityException, IOException { */ @Test public void updateBinary20() throws SQLException, SecurityException, IOException { - String value = "hi"; - String updatedValue = "bye"; - createAndPopulateTable("binary(20)", "'" + value + "'"); - stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); - rs.updateBytes(1, updatedValue.getBytes()); - rs.updateRow(); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getBytes(1), updatedValue.getBytes())); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + String value = "hi"; + String updatedValue = "bye"; + createAndPopulateTable("binary(20)", "'" + value + "'"); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + rs.updateBytes(1, updatedValue.getBytes()); + rs.updateRow(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getBytes(1), updatedValue.getBytes())); + } } } @@ -520,28 +652,34 @@ public void updateBinary20() throws SQLException, SecurityException, IOException */ @Test public void insertTest() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 int)"); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + tableName + " values (?, ?)"); - - String[] col1Value = {"Hello", null}; - int[] col2Value = {1, 2}; - pstmt.setObject(1, "Hello"); - pstmt.setInt(2, 1); - pstmt.execute(); - pstmt.setObject(1, null); - pstmt.setInt(2, 2); - pstmt.execute(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - int i = 0; - rs.next(); - do { - assertEquals(rs.getObject(1), col1Value[i]); - assertEquals(rs.getObject(2), col2Value[i]); - i++; - } while (rs.next()); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 int)"); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?, ?)"); + + String[] col1Value = {"Hello", null}; + int[] col2Value = {1, 2}; + pstmt.setObject(1, "Hello"); + pstmt.setInt(2, 1); + pstmt.execute(); + pstmt.setObject(1, null); + pstmt.setInt(2, 2); + pstmt.execute(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + int i = 0; + rs.next(); + do { + assertEquals(rs.getObject(1), col1Value[i]); + assertEquals(rs.getObject(2), col2Value[i]); + i++; + } while (rs.next()); + } + } } /** @@ -551,16 +689,23 @@ public void insertTest() throws SQLException { */ @Test public void insertTestNull() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values ( ?)"); - - pstmt.setObject(1, null); - pstmt.execute(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getBoolean(1), false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values ( ?)")) { + + pstmt.setObject(1, null); + pstmt.execute(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getBoolean(1), false); + } + } } /** @@ -571,16 +716,24 @@ public void insertTestNull() throws SQLException { */ @Test public void insertSetObject() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values (?)"); - - pstmt.setObject(1, 2); - pstmt.execute(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), 2); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?)")) { + + pstmt.setObject(1, 2); + pstmt.execute(); + } + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), 2); + } + } } /** @@ -590,22 +743,29 @@ public void insertSetObject() throws SQLException { */ @Test public void callableStatementOutputIntTest() throws SQLException { - int value = 5; - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value + " AS " + "int" + "))"); - - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " - + tableName; - stmt.execute(sql); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getString(1), String.valueOf(value)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int value = 5; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST (" + + value + " AS " + "int" + "))"); + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName); + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getString(1), String.valueOf(value)); + if (null != cs) { + cs.close(); + } } } @@ -616,23 +776,30 @@ public void callableStatementOutputIntTest() throws SQLException { */ @Test public void callableStatementOutputDateTest() throws SQLException { - String value = "2015-05-08"; - - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST ('" + value + "' AS " + "date" + "))"); - - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " - + tableName; - stmt.execute(sql); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getString(1), String.valueOf(value)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "2015-05-08"; + + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST ('" + + value + "' AS " + "date" + "))"); + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName); + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getString(1), String.valueOf(value)); + if (null != cs) { + cs.close(); + } } } @@ -643,23 +810,30 @@ public void callableStatementOutputDateTest() throws SQLException { */ @Test public void callableStatementOutputTimeTest() throws SQLException { - String value = "12:26:27.123345"; - String returnValue = "12:26:27"; - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST ('" + value + "' AS " + "time(3)" + "))"); - - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " - + tableName; - stmt.execute(sql); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT, 3); - cs.execute(); - assertEquals(String.valueOf(returnValue), "" + cs.getObject(1)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "12:26:27.123345"; + String returnValue = "12:26:27"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST ('" + + value + "' AS " + "time(3)" + "))"); + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName); + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT, 3); + cs.execute(); + assertEquals(String.valueOf(returnValue), "" + cs.getObject(1)); + if (null != cs) { + cs.close(); + } } } @@ -670,27 +844,36 @@ public void callableStatementOutputTimeTest() throws SQLException { */ @Test public void callableStatementOutputBinaryTest() throws SQLException { - byte[] binary20 = RandomData.generateBinaryTypes("20", false, false); - byte[] secondBinary20 = RandomData.generateBinaryTypes("20", false, false); - 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(); - 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); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?,?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(2, secondBinary20, microsoft.sql.Types.SQL_VARIANT); - - cs.execute(); - assertTrue(parseByte((byte[]) cs.getBytes(1), binary20)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + byte[] binary20 = RandomData.generateBinaryTypes("20", false, false); + byte[] secondBinary20 = RandomData.generateBinaryTypes("20", false, false); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant)"); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?,?)")) { + pstmt.setObject(1, binary20); + pstmt.setObject(2, secondBinary20); + pstmt.execute(); + } + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1 "; + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(2, secondBinary20, microsoft.sql.Types.SQL_VARIANT); + + cs.execute(); + assertTrue(parseByte((byte[]) cs.getBytes(1), binary20)); + if (null != cs) { + cs.close(); + } } } @@ -701,24 +884,30 @@ public void callableStatementOutputBinaryTest() throws SQLException { */ @Test public void callableStatementInputOutputIntTest() throws SQLException { - int col1Value = 5; - int col2Value = 2; - 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 + ")"); - 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); - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?,?) }"); - - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(2, col2Value, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getObject(1), col1Value); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int col1Value = 5; + int col2Value = 2; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 int)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" + "), " + col2Value + ")"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1"; + stmt.execute(sql); + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(2, col2Value, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getObject(1), col1Value); + if (null != cs) { + cs.close(); + } } } @@ -729,27 +918,33 @@ public void callableStatementInputOutputIntTest() throws SQLException { */ @Test public void callableStatementInputOutputReturnIntTest() throws SQLException { - int col1Value = 5; - int col2Value = 2; - int returnValue = 12; - 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 + ")"); - 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); - CallableStatement cs = con.prepareCall(" {? = call " + inputProc + " (?,?) }"); - - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getString(1), String.valueOf(returnValue)); - assertEquals(cs.getString(2), String.valueOf(col1Value)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int col1Value = 5; + int col2Value = 2; + int returnValue = 12; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 int)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" + "), " + col2Value + ")"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1" + " return " + returnValue; + stmt.execute(sql); + CallableStatement cs = con + .prepareCall(" {? = call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getString(1), String.valueOf(returnValue)); + assertEquals(cs.getString(2), String.valueOf(col1Value)); + if (null != cs) { + cs.close(); + } } } @@ -760,28 +955,35 @@ public void callableStatementInputOutputReturnIntTest() throws SQLException { */ @Test public void callableStatementInputOutputReturnStringTest() throws SQLException { - String col1Value = "aa"; - String col2Value = "bb"; - int returnValue = 12; - - 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)" + ")" + ")"); - 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); - CallableStatement cs = con.prepareCall(" {? = call " + inputProc + " (?,?) }"); - cs.registerOutParameter(1, java.sql.Types.INTEGER); - cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); - - cs.execute(); - assertEquals(returnValue, cs.getObject(1)); - assertEquals(cs.getObject(2), col1Value); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String col1Value = "aa"; + String col2Value = "bb"; + int returnValue = 12; + + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(col1,col2) values" + + " (CAST ('" + col1Value + "' AS " + "varchar(5)" + ")" + " ,CAST ('" + col2Value + "' AS " + + "varchar(5)" + ")" + ")"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1 " + " return " + returnValue; + stmt.execute(sql); + CallableStatement cs = con + .prepareCall(" {? = call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + cs.registerOutParameter(1, java.sql.Types.INTEGER); + cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); + + cs.execute(); + assertEquals(returnValue, cs.getObject(1)); + assertEquals(cs.getObject(2), col1Value); + if (null != cs) { + cs.close(); + } } } @@ -792,23 +994,26 @@ public void callableStatementInputOutputReturnStringTest() throws SQLException { */ @Test public void readSeveralRows() throws SQLException { - short value1 = 5; - int value2 = 10; - String value3 = "hi"; - 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)" + ")" + ")"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value1); - assertEquals(rs.getObject(2), value2); - assertEquals(rs.getObject(3), value3); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + short value1 = 5; + int value2 = 10; + String value3 = "hi"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant, col3 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST (" + + value1 + " AS " + "tinyint" + ")" + ",CAST (" + value2 + " AS " + "int" + ")" + ",CAST ('" + + value3 + "' AS " + "char(2)" + ")" + ")"); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value1); + assertEquals(rs.getObject(2), value2); + assertEquals(rs.getObject(3), value3); + } } - } /** @@ -818,12 +1023,16 @@ public void readSeveralRows() throws SQLException { */ @Test public void readVarcharInteger() throws SQLException { - Object expected[] = {"abc", 42}; - int index = 0; - rs = (SQLServerResultSet) stmt - .executeQuery("SELECT cast('abc' as sql_variant) UNION ALL SELECT cast(42 as sql_variant)"); - while (rs.next()) { - assertEquals(rs.getObject(1), expected[index++]); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + Object expected[] = {"abc", 42}; + int index = 0; + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT cast('abc' as sql_variant) UNION ALL SELECT cast(42 as sql_variant)")) { + while (rs.next()) { + assertEquals(rs.getObject(1), expected[index++]); + } + } } } @@ -834,17 +1043,19 @@ public void readVarcharInteger() throws SQLException { */ @Test public void testUnsupportedDatatype() throws SQLException { - rs = (SQLServerResultSet) stmt - .executeQuery("select cast(cast('2017-08-16 17:31:09.995 +07:00' as datetimeoffset) as sql_variant)"); - rs.next(); - try { - rs.getObject(1); - fail(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (Exception e) { - assertTrue(e.getMessage().equalsIgnoreCase("Unexpected TDS type DATETIMEOFFSETN in SQL_VARIANT.")); - } - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "select cast(cast('2017-08-16 17:31:09.995 +07:00' as datetimeoffset) as sql_variant)")) { + rs.next(); + try { + rs.getObject(1); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (Exception e) { + assertTrue( + e.getMessage().equalsIgnoreCase("Unexpected TDS type DATETIMEOFFSETN in SQL_VARIANT.")); + } + } } } @@ -856,10 +1067,13 @@ public void testUnsupportedDatatype() throws SQLException { */ @Test public void testTimeClassAsSqlVariant() throws SQLException { - rs = (SQLServerResultSet) stmt.executeQuery("select cast(cast('17:31:09.995' as time(3)) as sql_variant)"); - rs.next(); - Object object = rs.getObject(1); - assertEquals(object.getClass(), java.sql.Time.class);; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select cast(cast('17:31:09.995' as time(3)) as sql_variant)")) { + rs.next(); + Object object = rs.getObject(1); + assertEquals(object.getClass(), java.sql.Time.class);; + } } private boolean parseByte(byte[] expectedData, byte[] retrieved) { @@ -879,9 +1093,14 @@ private boolean parseByte(byte[] expectedData, byte[] retrieved) { * @throws SQLException */ private void createAndPopulateTable(String columnType, Object value) throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value + " AS " + columnType + "))"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST (" + + value + " AS " + columnType + "))"); + } } /** @@ -893,8 +1112,8 @@ private void createAndPopulateTable(String columnType, Object value) throws SQLE */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { - con = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = con.createStatement(); + tableName = RandomUtil.getIdentifier("sqlVariantTestSrcTable"); + inputProc = RandomUtil.getIdentifier("sqlVariantProc"); } /** @@ -904,24 +1123,10 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - TestUtils.dropProcedureIfExists(inputProc, stmt); - TestUtils.dropTableIfExists(tableName, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != pstmt) { - pstmt.close(); - } - - if (null != rs) { - rs.close(); - } - - if (null != con) { - con.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } - } 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 6d35691d9..42d27d23b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -22,6 +22,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; @@ -30,6 +31,7 @@ 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.sqlType.SqlDate; @@ -40,9 +42,10 @@ public class TVPWithSqlVariantTest extends AbstractTest { private static SQLServerConnection conn = null; static SQLServerStatement stmt = null; static SQLServerDataTable tvp = null; - private static String tvpName = "numericTVP"; - private static String destTable = "destTvpSqlVariantTable"; - private static String procedureName = "procedureThatCallsTVP"; + + private static String tvpName = RandomUtil.getIdentifier("numericTVP"); + private static String destTable = RandomUtil.getIdentifier("destTvpSqlVariantTable"); + private static String procedureName = RandomUtil.getIdentifier("procedureThatCallsTVP"); /** * Test a previous failure regarding to numeric precision. Issue #211 @@ -56,13 +59,14 @@ public void testInt() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(12); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getInt(1), 12); assertEquals(rs.getString(1), "" + 12); @@ -84,13 +88,14 @@ public void testDate() throws SQLException { tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(date); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), "" + date); // TODO: GetDate has issues } @@ -109,13 +114,14 @@ public void testMoney() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(new BigDecimal(numeric[14])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getMoney(1), new BigDecimal(numeric[14])); } @@ -134,14 +140,15 @@ public void testSmallInt() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Short.valueOf(numeric[2])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(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 @@ -164,12 +171,13 @@ public void testBigInt() throws SQLException { String[] numeric = createNumericValues(); tvp.addRow(Long.parseLong(numeric[4])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getLong(1), Long.parseLong(numeric[4])); } @@ -188,12 +196,13 @@ public void testBoolean() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Boolean.parseBoolean(numeric[0])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getBoolean(1), Boolean.parseBoolean(numeric[0])); } @@ -212,12 +221,13 @@ public void testFloat() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Float.parseFloat(numeric[1])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getFloat(1), Float.parseFloat(numeric[1])); } @@ -236,12 +246,13 @@ public void testNvarChar() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String colValue = "س"; tvp.addRow(colValue); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), colValue); } @@ -265,12 +276,13 @@ public void testVarChar8000() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -294,8 +306,8 @@ public void testLongVarChar() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); try { pstmt.execute(); @@ -322,12 +334,13 @@ public void testDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(timestamp); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), "" + timestamp); // System.out.println(rs.getDateTime(1));// TODO does not work @@ -351,14 +364,14 @@ public void testNull() throws SQLException { assertTrue(e.getMessage().startsWith("Use of TVPs containing null sql_variant columns is not supported.")); } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { - System.out.println(rs.getString(1)); } } } @@ -372,19 +385,17 @@ public void testNull() throws SQLException { @Test public void testIntStoredProcedure() throws SQLException { java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0"); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(timestamp); - SQLServerCallableStatement Cstatement = (SQLServerCallableStatement) conn.prepareCall(sql); - Cstatement.setStructured(1, tvpName, tvp); - Cstatement.execute(); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + destTable)) { - while (rs.next()) { - System.out.println(rs.getString(1)); - } - if (null != Cstatement) { - Cstatement.close(); + try (SQLServerCallableStatement cstatement = (SQLServerCallableStatement) conn.prepareCall(sql)) { + cstatement.setStructured(1, tvpName, tvp); + cstatement.execute(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(destTable))) { + while (rs.next()) { + } } } } @@ -459,8 +470,8 @@ public void testSetup() throws SQLException { .getConnection(connectionString + ";sendStringParametersAsUnicode=true;"); stmt = (SQLServerStatement) conn.createStatement(); - TestUtils.dropProcedureIfExists(procedureName, stmt); - TestUtils.dropTableIfExists(destTable, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); dropTVPS(); createTVPS(); @@ -469,31 +480,34 @@ public void testSetup() throws SQLException { } 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); + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); } private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + destTable + " SELECT * FROM @InputData" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(destTable) + " SELECT * FROM @InputData" + " END"; stmt.execute(sql); } private void createTables() throws SQLException { - String sql = "create table " + destTable + " (c1 sql_variant null);"; + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (c1 sql_variant null);"; stmt.execute(sql); } private void createTVPS() throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 sql_variant null)"; + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + + " as table (c1 sql_variant null)"; stmt.executeUpdate(TVPCreateCmd); } @AfterEach public void terminateVariation() throws SQLException { - TestUtils.dropProcedureIfExists(procedureName, stmt); - TestUtils.dropTableIfExists(destTable, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); dropTVPS(); } @@ -511,7 +525,5 @@ public static void afterAll() throws SQLException { 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 4fc9df03a..d7814f66a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java @@ -14,14 +14,17 @@ import java.sql.Statement; import java.text.MessageFormat; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -53,7 +56,7 @@ public void testBulkCSVFileRecordExceptionCause() throws Exception { } } - String waitForDelaySPName = "waitForDelaySP"; + static String waitForDelaySPName = RandomUtil.getIdentifier("waitForDelaySP"); final int waitForDelaySeconds = 10; /** @@ -66,13 +69,14 @@ public void testBulkCSVFileRecordExceptionCause() throws Exception { public void testSocketTimeoutExceptionCause() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - TestUtils.dropProcedureIfExists(waitForDelaySPName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); createWaitForDelayPreocedure(conn); } + try (Connection conn = DriverManager .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); Statement stmt = conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof SQLException)) { @@ -87,8 +91,16 @@ public void testSocketTimeoutExceptionCause() throws Exception { } private void createWaitForDelayPreocedure(SQLServerConnection conn) throws SQLException { - String sql = "CREATE PROCEDURE " + waitForDelaySPName + " AS" + " BEGIN" + " WAITFOR DELAY '00:00:" - + waitForDelaySeconds + "';" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName) + " AS" + " BEGIN" + + " WAITFOR DELAY '00:00:" + waitForDelaySeconds + "';" + " END"; conn.createStatement().execute(sql); } + + @AfterAll + public static void cleanup() throws SQLException { + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); + } + } } 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 d6b4d00e3..c4f3151cc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java @@ -20,12 +20,13 @@ import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class ParameterMetaDataTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("Statement'Param") + "]"; + private static final String tableName = RandomUtil.getIdentifier("StatementParam"); /** * Test ParameterMetaData#isWrapperFor and ParameterMetaData#unwrap. @@ -36,9 +37,10 @@ public class ParameterMetaDataTest extends AbstractTest { public void testParameterMetaDataWrapper() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " (col1 int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int identity(1,1) primary key)"); try { - String query = "SELECT * from " + tableName + " where col1 = ?"; + String query = "SELECT * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col1 = ?"; try (PreparedStatement pstmt = con.prepareStatement(query)) { ParameterMetaData parameterMetaData = pstmt.getParameterMetaData(); @@ -46,7 +48,7 @@ public void testParameterMetaDataWrapper() throws SQLException { assertSame(parameterMetaData, parameterMetaData.unwrap(ParameterMetaData.class)); } } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -77,15 +79,17 @@ public void testSQLServerExceptionNotWrapped() throws SQLException { public void testNameWithBraces() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " ([c1_varchar(max)] varchar(max))"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)] varchar(max))"); try { - String query = "insert into " + tableName + " ([c1_varchar(max)]) values (?)"; + String query = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)]) values (?)"; try (PreparedStatement pstmt = con.prepareStatement(query)) { pstmt.getParameterMetaData(); } } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -99,9 +103,11 @@ public void testNameWithBraces() throws SQLException { public void testParameterMetaData() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " ([c1_varchar(max)] varchar(max), c2 decimal(38,5))"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)] varchar(max), c2 decimal(38,5))"); try { - String query = "insert into " + tableName + " ([c1_varchar(max)], c2) values (?,?)"; + String query = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)], c2) values (?,?)"; try (PreparedStatement pstmt = con.prepareStatement(query)) { ParameterMetaData metadata = pstmt.getParameterMetaData(); @@ -112,7 +118,7 @@ public void testParameterMetaData() throws SQLException { assert (metadata.getScale(2) == 5); } } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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 2cb73ee5b..387451b78 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java @@ -22,37 +22,32 @@ 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; @RunWith(JUnitPlatform.class) public class ParameterMetaDataWhiteSpaceTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("ParameterMetaDataWhiteSpaceTest") + "]"; - - private static Statement stmt = null; + private static final String tableName = RandomUtil.getIdentifier("ParameterMetaDataWhiteSpaceTest"); @BeforeAll public static void BeforeTests() throws SQLException { - connection = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = connection.createStatement(); createCharTable(); } @AfterAll public static void dropTables() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != connection) { - connection.close(); + try (SQLServerConnection connection = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } private static void createCharTable() throws SQLException { - stmt.execute("Create table " + tableName + " (c1 int)"); + try (SQLServerConnection connection = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1 int)"); + } } /** @@ -62,8 +57,10 @@ private static void createCharTable() throws SQLException { */ @Test public void NormalTest() throws SQLException { - testUpdateWithTwoParameters("update " + tableName + " set c1 = ? where c1 = ?"); - testInsertWithOneParameter("insert into " + tableName + " (c1) values (?)"); + testUpdateWithTwoParameters( + "update " + AbstractSQLGenerator.escapeIdentifier(tableName) + " set c1 = ? where c1 = ?"); + testInsertWithOneParameter( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1) values (?)"); } /** @@ -97,13 +94,20 @@ public void FormFeedTest() throws SQLException { } private void testQueriesWithWhiteSpaces(String whiteSpace) throws SQLException { - testUpdateWithTwoParameters("update" + whiteSpace + tableName + " set c1 = ? where c1 = ?"); - testUpdateWithTwoParameters("update " + tableName + " set" + whiteSpace + "c1 = ? where c1 = ?"); - testUpdateWithTwoParameters("update " + tableName + " set c1 = ? where" + whiteSpace + "c1 = ?"); - - testInsertWithOneParameter("insert into " + tableName + "(c1) values (?)"); // no space between table name and - // column name - testInsertWithOneParameter("insert into" + whiteSpace + tableName + " (c1) values (?)"); + testUpdateWithTwoParameters( + "update" + whiteSpace + AbstractSQLGenerator.escapeIdentifier(tableName) + " set c1 = ? where c1 = ?"); + testUpdateWithTwoParameters("update " + AbstractSQLGenerator.escapeIdentifier(tableName) + " set" + whiteSpace + + "c1 = ? where c1 = ?"); + testUpdateWithTwoParameters("update " + AbstractSQLGenerator.escapeIdentifier(tableName) + " set c1 = ? where" + + whiteSpace + "c1 = ?"); + + testInsertWithOneParameter( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(c1) values (?)"); // no space + // between table + // name and + // column name + testInsertWithOneParameter( + "insert into" + whiteSpace + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1) values (?)"); } private void testUpdateWithTwoParameters(String sql) throws SQLException { @@ -127,14 +131,16 @@ private void testInsertWithOneParameter(String sql) throws SQLException { } private void insertTestRow(int id) throws SQLException { - try (PreparedStatement ps = connection.prepareStatement("insert into " + tableName + " (c1) values (?)")) { + try (PreparedStatement ps = connection.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1) values (?)")) { ps.setInt(1, id); ps.executeUpdate(); } } private boolean isIdPresentInTable(int id) throws SQLException { - try (PreparedStatement ps = connection.prepareStatement("select c1 from " + tableName + " where c1 = ?")) { + try (PreparedStatement ps = connection.prepareStatement( + "select c1 from " + AbstractSQLGenerator.escapeIdentifier(tableName) + " where c1 = ?")) { ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { return rs.next(); 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 2cad394a1..80f13604c 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java @@ -26,31 +26,34 @@ import com.microsoft.sqlserver.jdbc.Geography; import com.microsoft.sqlserver.jdbc.Geometry; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class BatchExecutionWithBulkCopyTest extends AbstractTest { - static long UUID = System.currentTimeMillis();; - static String tableName = "BulkCopyParseTest" + UUID; - static String tableNameBulk = "BulkCopyParseTest" + UUID; - static String unsupportedTableName = "[BulkCopyUnsupportedTable'" + UUID + "]"; - static String squareBracketTableName = "[BulkCopy]]]]test'" + UUID + "]"; - static String doubleQuoteTableName = "\"BulkCopy\"\"\"\"test'" + UUID + "\""; + static String tableName = RandomUtil.getIdentifier("BulkCopyParseTest"); + static String tableNameBulk = RandomUtil.getIdentifier("BulkCopyParseTest"); + static String unsupportedTableName = RandomUtil.getIdentifier("BulkCopyUnsupportedTable'"); + static String squareBracketTableName = RandomUtil.getIdentifier("BulkCopy]]]]test'"); + static String doubleQuoteTableName = RandomUtil.getIdentifier("\"BulkCopy\"\"\"\"test\""); + static String schemaTableName = "\"dbo\" . /*some comment */ " + squareBracketTableName; @Test public void testIsInsert() throws Exception { try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - String valid1 = "INSERT INTO " + tableNameBulk + " values (1, 2)"; - String valid2 = " INSERT INTO " + tableNameBulk + " values (1, 2)"; - String valid3 = "/* asdf */ INSERT INTO " + tableNameBulk + " values (1, 2)"; - String invalid = "Select * from " + tableNameBulk; + String valid1 = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " values (1, 2)"; + String valid2 = " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " values (1, 2)"; + String valid3 = "/* asdf */ INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + + " values (1, 2)"; + String invalid = "Select * from " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk); Method method = stmt.getClass().getDeclaredMethod("isInsert", String.class); method.setAccessible(true); @@ -65,7 +68,8 @@ public void testIsInsert() throws Exception { public void testComments() throws Exception { try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); PreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement("");) { - String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ tableNameBulk /*rando comment */" + String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ " + + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " /*rando comment */" + " /* rando comment */values/* rando comment */ (1, 2)"; Field f1 = pstmt.getClass().getDeclaredField("localUserSQL"); @@ -76,7 +80,8 @@ public void testComments() throws Exception { boolean.class, boolean.class, boolean.class); method.setAccessible(true); - assertEquals("tableNameBulk", (String) method.invoke(pstmt, false, false, false, false)); + assertEquals(AbstractSQLGenerator.escapeIdentifier(tableNameBulk), + (String) method.invoke(pstmt, false, false, false, false)); } } @@ -155,8 +160,8 @@ public void testAll() throws Exception { @Test public void testAllcolumns() throws Exception { - String valid = "INSERT INTO " + tableName + " values " + "(" + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " - + "?, " + "?, " + "? " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values " + "(" + "?, " + + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "? " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -182,7 +187,8 @@ public void testAllcolumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -206,8 +212,8 @@ public void testAllcolumns() throws Exception { @Test public void testMixColumns() throws Exception { - String valid = "INSERT INTO " + tableName + " (c1, c3, c5, c8) values " + "(" + "?, " + "?, " + "?, " + "? " - + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1, c3, c5, c8) values " + + "(" + "?, " + "?, " + "?, " + "? " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -228,7 +234,8 @@ public void testMixColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -254,8 +261,9 @@ public void testMixColumns() throws Exception { @Test public void testNullOrEmptyColumns() throws Exception { - String valid = "INSERT INTO " + tableName + " (c1, c2, c3, c4, c5, c6, c7) values " + "(" + "?, " + "?, " - + "?, " + "?, " + "?, " + "?, " + "? " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (c1, c2, c3, c4, c5, c6, c7) values " + "(" + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "? " + + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -275,7 +283,8 @@ public void testNullOrEmptyColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -300,8 +309,8 @@ public void testNullOrEmptyColumns() throws Exception { // Non-parameterized queries are not supported anymore. // @Test public void testAllFilledColumns() throws Exception { - String valid = "INSERT INTO " + tableName + " values " + "(" + "1234, " + "false, " + "a, " + "null, " - + "null, " + "123.45, " + "b, " + "varc, " + "sadf, " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values " + "(" + "1234, " + + "false, " + "a, " + "null, " + "null, " + "123.45, " + "b, " + "varc, " + "sadf, " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -314,7 +323,8 @@ public void testAllFilledColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -338,7 +348,7 @@ public void testAllFilledColumns() throws Exception { @Test public void testSquareBracketAgainstDB() throws Exception { - String valid = "insert into " + squareBracketTableName + " values (?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + " values (?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -347,8 +357,9 @@ public void testSquareBracketAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(squareBracketTableName, stmt); - String createTable = "create table " + squareBracketTableName + " (c1 int)"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + + " (c1 int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -356,7 +367,8 @@ public void testSquareBracketAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -366,7 +378,7 @@ public void testSquareBracketAgainstDB() throws Exception { @Test public void testDoubleQuoteAgainstDB() throws Exception { - String valid = "insert into " + doubleQuoteTableName + " values (?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName) + " values (?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -375,8 +387,9 @@ public void testDoubleQuoteAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(doubleQuoteTableName, stmt); - String createTable = "create table " + doubleQuoteTableName + " (c1 int)"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName) + + " (c1 int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -384,7 +397,8 @@ public void testDoubleQuoteAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + doubleQuoteTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -394,8 +408,7 @@ public void testDoubleQuoteAgainstDB() throws Exception { @Test public void testSchemaAgainstDB() throws Exception { - String schemaTableName = "\"dbo\" . /*some comment */ " + squareBracketTableName; - String valid = "insert into " + schemaTableName + " values (?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(schemaTableName) + " values (?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -404,9 +417,8 @@ public void testSchemaAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists("[dbo]." + squareBracketTableName, stmt); - - String createTable = "create table " + schemaTableName + " (c1 int)"; + TestUtils.dropTableIfExists("[dbo]." + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(schemaTableName) + " (c1 int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -414,7 +426,8 @@ public void testSchemaAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + schemaTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(schemaTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -424,7 +437,8 @@ public void testSchemaAgainstDB() throws Exception { @Test public void testColumnNameMixAgainstDB() throws Exception { - String valid = "insert into " + squareBracketTableName + " ([c]]]]1], [c]]]]2]) values (?, 1)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + + " ([c]]]]1], [c]]]]2]) values (?, 1)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -433,8 +447,9 @@ public void testColumnNameMixAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(squareBracketTableName, stmt); - String createTable = "create table " + squareBracketTableName + " ([c]]]]1] int, [c]]]]2] int)"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + + " ([c]]]]1] int, [c]]]]2] int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -442,7 +457,8 @@ public void testColumnNameMixAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -452,8 +468,8 @@ public void testColumnNameMixAgainstDB() throws Exception { @Test public void testAllColumnsLargeBatch() throws Exception { - String valid = "INSERT INTO " + tableName + " values " + "(" + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " - + "?, " + "?, " + "? " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values " + "(" + "?, " + + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "? " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -479,7 +495,8 @@ public void testAllColumnsLargeBatch() throws Exception { pstmt.executeLargeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -503,7 +520,7 @@ public void testAllColumnsLargeBatch() throws Exception { @Test public void testIllegalNumberOfArgNoColumnList() throws Exception { - String invalid = "insert into " + tableName + " values (?, ?,? ,?) "; + String invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?, ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -524,7 +541,8 @@ public void testIllegalNumberOfArgNoColumnList() throws Exception { assertEquals("Column name or number of supplied values does not match table definition.", e.getMessage()); } - invalid = "insert into " + tableName + " (c1, c2, c3) values (?, ?,? ,?) "; + invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (c1, c2, c3) values (?, ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -550,7 +568,8 @@ public void testIllegalNumberOfArgNoColumnList() throws Exception { @Test public void testNonParameterizedQuery() throws Exception { - String invalid = "insert into " + tableName + " values ((SELECT * from table where c1=?), ?,? ,?) "; + String invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " values ((SELECT * from table where c1=?), ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -571,7 +590,7 @@ public void testNonParameterizedQuery() throws Exception { assertEquals("Incorrect syntax near the keyword 'table'.", e.getMessage()); } - invalid = "insert into " + tableName + " values ('?', ?,? ,?) "; + invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values ('?', ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -594,7 +613,8 @@ public void testNonParameterizedQuery() throws Exception { @Test public void testNonSupportedColumns() throws Exception { - String valid = "insert into " + unsupportedTableName + " values (?, ?, ?, ?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(unsupportedTableName) + + " values (?, ?, ?, ?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -603,9 +623,9 @@ public void testNonSupportedColumns() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(unsupportedTableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(unsupportedTableName), stmt); - String createTable = "create table " + unsupportedTableName + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(unsupportedTableName) + " (c1 geometry, c2 geography, c3 datetime, c4 smalldatetime)"; stmt.execute(createTable); @@ -621,7 +641,8 @@ public void testNonSupportedColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + unsupportedTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(unsupportedTableName))) { rs.next(); assertEquals(g1.toString(), Geometry.STGeomFromWKB((byte[]) rs.getObject(1)).toString()); assertEquals(g2.toString(), Geography.STGeomFromWKB((byte[]) rs.getObject(2)).toString()); @@ -636,10 +657,10 @@ public void testSetup() throws TestAbortedException, Exception { try (Connection connection = DriverManager .getConnection(connectionString + ";useBulkCopyForBatchInsert=true;")) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { - 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)" + ")"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(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)" + ")"; stmt.execute(sql1); } @@ -650,10 +671,12 @@ public void testSetup() throws TestAbortedException, Exception { public static void terminateVariation() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString)) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(squareBracketTableName, stmt); - TestUtils.dropTableIfExists(doubleQuoteTableName, stmt); - TestUtils.dropTableIfExists(unsupportedTableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameBulk), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(unsupportedTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(schemaTableName), 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 a41cf3c47..8694c91b6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -12,7 +12,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.sql.Types; import org.junit.jupiter.api.AfterAll; @@ -22,9 +21,11 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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; @@ -32,12 +33,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; - static PreparedStatement pstmt1 = null; - static ResultSet rs = null; + static String tableName = RandomUtil.getIdentifier("esimple"); /** * Test with combination of setString and setNull which cause the "Violation of PRIMARY KEY constraint and @@ -48,49 +44,49 @@ public class BatchExecutionWithNullTest extends AbstractTest { @Test public void testAddBatch2() throws SQLException { // try { - String sPrepStmt = "insert into esimple (id, name) values (?, ?)"; + String sPrepStmt = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id, name) values (?, ?)"; int updateCountlen = 0; int key = 42; // 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(); - - pstmt.setInt(1, key++); - pstmt.setString(2, "FOO"); - pstmt.addBatch(); - - pstmt.setInt(1, key++); - pstmt.setNull(2, Types.VARCHAR); - pstmt.addBatch(); + try (Connection conn = DriverManager.getConnection(connectionString); + PreparedStatement pstmt = conn.prepareStatement(sPrepStmt)) { + pstmt.setInt(1, key++); + pstmt.setNull(2, Types.VARCHAR); + pstmt.addBatch(); - int[] updateCount = pstmt.executeBatch(); - updateCountlen += updateCount.length; + pstmt.setInt(1, key++); + pstmt.setString(2, "FOO"); + pstmt.addBatch(); - pstmt.setInt(1, key++); - pstmt.setString(2, "BAR"); - pstmt.addBatch(); + pstmt.setInt(1, key++); + pstmt.setNull(2, Types.VARCHAR); + pstmt.addBatch(); - pstmt.setInt(1, key++); - pstmt.setNull(2, Types.VARCHAR); - pstmt.addBatch(); + int[] updateCount = pstmt.executeBatch(); + updateCountlen += updateCount.length; - updateCount = pstmt.executeBatch(); - updateCountlen += updateCount.length; + pstmt.setInt(1, key++); + pstmt.setString(2, "BAR"); + pstmt.addBatch(); - assertTrue(updateCountlen == 5, TestResource.getResource("R_addBatchFailed")); + pstmt.setInt(1, key++); + pstmt.setNull(2, Types.VARCHAR); + pstmt.addBatch(); - String sPrepStmt1 = "select count(*) from esimple"; + updateCount = pstmt.executeBatch(); + updateCountlen += updateCount.length; - pstmt1 = connection.prepareStatement(sPrepStmt1); - rs = pstmt1.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 5, TestResource.getResource("R_insertBatchFailed")); - pstmt1.close(); + assertTrue(updateCountlen == 5, TestResource.getResource("R_addBatchFailed")); + } + String sPrepStmt1 = "select count(*) from " + AbstractSQLGenerator.escapeIdentifier(tableName); + try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1); ResultSet rs = pstmt1.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 5, TestResource.getResource("R_insertBatchFailed")); + pstmt1.close(); + } } /** @@ -100,8 +96,10 @@ public void testAddBatch2() throws SQLException { */ @Test public void testAddbatch2AEOnConnection() throws SQLException { - connection = DriverManager.getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); - testAddBatch2(); + try (Connection connection = DriverManager + .getConnection(connectionString + ";columnEncryptionSetting=Enabled;")) { + testAddBatch2(); + } } @BeforeEach @@ -110,35 +108,21 @@ public void testSetup() throws TestAbortedException, Exception { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - connection = DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) connection.createStatement(); - 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(); + try (Connection connection = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id integer not null, name varchar(255), constraint pk_esimple primary key (id))"; + stmt.execute(sql1); + stmt.close(); + } } @AfterAll public static void terminateVariation() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - TestUtils.dropTableIfExists("esimple", stmt); - } - - if (null != pstmt) { - pstmt.close(); - } - if (null != pstmt1) { - pstmt1.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } - if (null != conn) { - conn.close(); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } 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 3ba34122b..749e7a799 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java @@ -22,9 +22,11 @@ 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; @@ -35,7 +37,10 @@ */ @RunWith(JUnitPlatform.class) public class RegressionTest extends AbstractTest { - static Connection con = null; + + static String tableName = RandomUtil.getIdentifier("PrepareDStatementTestTable"); + static String tableName2 = RandomUtil.getIdentifier("PrepareDStatementTestTable2"); + static String schemaName = RandomUtil.getIdentifier("schemaName"); /** * Setup before test @@ -44,9 +49,8 @@ public class RegressionTest extends AbstractTest { */ @BeforeAll public static void setupTest() throws SQLException { - con = DriverManager.getConnection(connectionString); - try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("x", stmt); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } @@ -57,8 +61,11 @@ public static void setupTest() throws SQLException { */ @Test public void createViewTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create view x as select 1 a"); - PreparedStatement pstmt2 = con.prepareStatement("drop view x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create view " + AbstractSQLGenerator.escapeIdentifier(tableName) + " as select 1 a"); + PreparedStatement pstmt2 = con + .prepareStatement("drop view " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { @@ -74,8 +81,11 @@ public void createViewTest() throws SQLException { */ @Test public void createSchemaTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create schema x"); - PreparedStatement pstmt2 = con.prepareStatement("drop schema x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con + .prepareStatement("create schema " + AbstractSQLGenerator.escapeIdentifier(schemaName)); + PreparedStatement pstmt2 = con + .prepareStatement("drop schema " + AbstractSQLGenerator.escapeIdentifier(schemaName))) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { @@ -91,8 +101,11 @@ public void createSchemaTest() throws SQLException { */ @Test public void createTableTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create table x (col1 int)"); - PreparedStatement pstmt2 = con.prepareStatement("drop table x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); + PreparedStatement pstmt2 = con + .prepareStatement("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { @@ -108,9 +121,13 @@ public void createTableTest() throws SQLException { */ @Test public void alterTableTest() throws SQLException { - 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")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); + PreparedStatement pstmt2 = con.prepareStatement( + "ALTER TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " ADD column_name char;"); + PreparedStatement pstmt3 = con + .prepareStatement("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); pstmt3.execute(); @@ -127,10 +144,15 @@ public void alterTableTest() throws SQLException { */ @Test public void grantTest() throws SQLException { - 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")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); + PreparedStatement pstmt2 = con.prepareStatement( + "grant select on " + AbstractSQLGenerator.escapeIdentifier(tableName) + " to public"); + PreparedStatement pstmt3 = con.prepareStatement( + "revoke select on " + AbstractSQLGenerator.escapeIdentifier(tableName) + " from public"); + PreparedStatement pstmt4 = con + .prepareStatement("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); pstmt3.execute(); @@ -163,18 +185,21 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), 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;"); + stmt.execute("if object_id('" + TestUtils.escapeSingleQuotes(tableName2) + + "', 'U') is not null\ndrop table " + AbstractSQLGenerator.escapeIdentifier(tableName2)); if (createPrimaryKey) { - stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max), primary key (ID) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max), primary key (ID) );"); } else { - stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max) );"); } } catch (Exception e) { fail(e.toString()); @@ -191,7 +216,8 @@ 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 (PreparedStatement pstmt = con.prepareStatement("insert into TEST_TABLE values (?,?)")) { + try (PreparedStatement pstmt = con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName2) + " values (?,?)")) { // 0,a pstmt.setInt(1, 0); pstmt.setNString(2, values[0]); @@ -226,7 +252,8 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { // check the data in the table Map selectedValues = new LinkedHashMap<>(); int id = 0; - try (PreparedStatement pstmt = con.prepareStatement("select * from TEST_TABLE;")) { + try (PreparedStatement pstmt = con + .prepareStatement("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName2) + ";")) { try (ResultSet rs = pstmt.executeQuery()) { int i = 0; while (rs.next()) { @@ -240,7 +267,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } } } finally { - TestUtils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); } } } @@ -253,19 +280,22 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { */ @Test public void addBatchWithLargeStringTest() throws SQLException { - try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("TEST_TABLE", stmt); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), 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;"); + stmt.execute("if object_id('" + TestUtils.escapeSingleQuotes(tableName2) + + "', 'U') is not null\ndrop table " + AbstractSQLGenerator.escapeIdentifier(tableName2)); if (createPrimaryKey) { - stmt.execute("create table testTable ( ID int, DATA nvarchar(max), primary key (ID) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max), primary key (ID) );"); } else { - stmt.execute("create table testTable ( ID int, DATA nvarchar(max) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max) );"); } } catch (Exception e) { fail(e.toString()); @@ -280,7 +310,8 @@ public void addBatchWithLargeStringTest() throws SQLException { String largeString = stringBuilder.toString(); // insert five rows into the table; use a batch for each row - try (PreparedStatement pstmt = con.prepareStatement("insert into testTable values (?,?), (?,?);")) { + try (PreparedStatement pstmt = con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName2) + " values (?,?), (?,?);")) { // 0,a // 1,b pstmt.setInt(1, 0); @@ -329,7 +360,7 @@ public void addBatchWithLargeStringTest() throws SQLException { catch (Exception e) { fail(e.toString()); } finally { - TestUtils.dropTableIfExists("testTable", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); } } } @@ -341,12 +372,9 @@ public void addBatchWithLargeStringTest() throws SQLException { */ @AfterAll public static void cleanup() throws SQLException { - try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("x", stmt); - TestUtils.dropTableIfExists("TEST_TABLE", stmt); - } - if (null != con) { - con.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); } } 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 eb9bd0c3e..098f789d5 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java @@ -18,12 +18,13 @@ import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.jdbc.dataclassification.SensitivityProperty; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class DataClassificationTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("DataClassification") + "]"; + private static final String tableName = RandomUtil.getIdentifier("DataClassification"); /** * Tests data classification metadata information from SQL Server @@ -38,7 +39,7 @@ public void testDataClassificationMetadata() throws Exception { if (TestUtils.serverSupportsDataClassification(stmt)) { createTable(connection, stmt); runTestsForServer(stmt); - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -51,26 +52,26 @@ public void testDataClassificationMetadata() throws Exception { * @throws SQLException */ private void createTable(Connection connection, Statement stmt) throws SQLException { - String createQuery = "CREATE TABLE " + tableName + " (" + "[Id] [int] IDENTITY(1,1) NOT NULL," - + "[CompanyName] [nvarchar](40) NOT NULL," + "[ContactName] [nvarchar](50) NULL," - + "[ContactTitle] [nvarchar](40) NULL," + "[City] [nvarchar](40) NULL," - + "[CountryName] [nvarchar](40) NULL," + String createQuery = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (" + + "[Id] [int] IDENTITY(1,1) NOT NULL," + "[CompanyName] [nvarchar](40) NOT NULL," + + "[ContactName] [nvarchar](50) NULL," + "[ContactTitle] [nvarchar](40) NULL," + + "[City] [nvarchar](40) NULL," + "[CountryName] [nvarchar](40) NULL," + "[Phone] [nvarchar](30) MASKED WITH (FUNCTION = 'default()') NULL," + "[Fax] [nvarchar](30) MASKED WITH (FUNCTION = 'default()') NULL)"; stmt.execute(createQuery); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".CompanyName WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Company name', INFORMATION_TYPE_ID='COMPANY')"); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".ContactName WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Person name', INFORMATION_TYPE_ID='NAME')"); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".Phone WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Contact Information', INFORMATION_TYPE_ID='CONTACT')"); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".Fax WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Contact Information', INFORMATION_TYPE_ID='CONTACT')"); // INSERT ROWS OF DATA - try (PreparedStatement ps = connection - .prepareStatement("INSERT INTO " + tableName + " VALUES (?,?,?,?,?,?,?)")) { + try (PreparedStatement ps = connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (?,?,?,?,?,?,?)")) { ps.setString(1, "Exotic Liquids"); ps.setString(2, "Charlotte Cooper"); @@ -108,7 +109,8 @@ private void createTable(Connection connection, Statement stmt) throws SQLExcept * @throws Exception */ private void runTestsForServer(Statement stmt) throws Exception { - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { verifySensitivityClassification(rs); } } 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 845f4a057..574a928df 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java @@ -34,12 +34,15 @@ import com.microsoft.sqlserver.jdbc.ISQLServerResultSet; import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class ResultSetTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("StatementParam") + "]"; + private static final String tableName = RandomUtil.getIdentifier("StatementParam"); + + static final String uuid = UUID.randomUUID().toString(); /** * Tests proper exception for unsupported operation @@ -49,37 +52,39 @@ public class ResultSetTest extends AbstractTest { @Test public void testJdbc41ResultSetMethods() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " ( " + "col1 int, " + "col2 varchar(512), " - + "col3 float, " + "col4 decimal(10,5), " + "col5 uniqueidentifier, " + "col6 xml, " - + "col7 varbinary(max), " + "col8 text, " + "col9 ntext, " + "col10 varbinary(max), " + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " ( " + "col1 int, " + + "col2 varchar(512), " + "col3 float, " + "col4 decimal(10,5), " + "col5 uniqueidentifier, " + + "col6 xml, " + "col7 varbinary(max), " + "col8 text, " + "col9 ntext, " + "col10 varbinary(max), " + "col11 date, " + "col12 time, " + "col13 datetime2, " + "col14 datetimeoffset, " + "col15 decimal(10,9), " + "col16 decimal(38,38), " + "order_column int identity(1,1) primary key)"); try { - stmt.executeUpdate("Insert into " + tableName + " values(" + "1, " // col1 - + "'hello', " // col2 - + "2.0, " // col3 - + "123.45, " // col4 - + "'6F9619FF-8B86-D011-B42D-00C04FC964FF', " // col5 - + "'', " // col6 - + "0x63C34D6BCAD555EB64BF7E848D02C376, " // col7 - + "'text', " // col8 - + "'ntext', " // col9 - + "0x63C34D6BCAD555EB64BF7E848D02C376," // col10 - + "'2017-05-19'," // col11 - + "'10:47:15.1234567'," // col12 - + "'2017-05-19T10:47:15.1234567'," // col13 - + "'2017-05-19T10:47:15.1234567+02:00'," // col14 - + "0.123456789, " // col15 - + "0.1234567890123456789012345678901234567" // col16 - + ")"); - - stmt.executeUpdate("Insert into " + tableName + " values(" + "null, " + "null, " + "null, " + "null, " + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(" + "1, " // col1 + + "'hello', " // col2 + + "2.0, " // col3 + + "123.45, " // col4 + + "'" + uuid + "', " // col5 + + "'', " // col6 + + "0x63C34D6BCAD555EB64BF7E848D02C376, " // col7 + + "'text', " // col8 + + "'ntext', " // col9 + + "0x63C34D6BCAD555EB64BF7E848D02C376," // col10 + + "'2017-05-19'," // col11 + + "'10:47:15.1234567'," // col12 + + "'2017-05-19T10:47:15.1234567'," // col13 + + "'2017-05-19T10:47:15.1234567+02:00'," // col14 + + "0.123456789, " // col15 + + "0.1234567890123456789012345678901234567" // col16 + + ")"); + + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(" + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " - + "null, " + "null, " + "null, " + "null)"); + + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null)"); - try (ResultSet rs = stmt.executeQuery("select * from " + tableName + " order by order_column")) { + try (ResultSet rs = stmt.executeQuery("select * from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " order by order_column")) { // test non-null values assertTrue(rs.next()); assertEquals(Byte.valueOf((byte) 1), rs.getObject(1, Byte.class)); @@ -105,9 +110,8 @@ public void testJdbc41ResultSetMethods() throws SQLException { assertEquals(0, rs.getObject(4, BigDecimal.class).compareTo(new BigDecimal("123.45"))); assertEquals(0, rs.getObject("col4", BigDecimal.class).compareTo(new BigDecimal("123.45"))); - assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), rs.getObject(5, UUID.class)); - assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), - rs.getObject("col5", UUID.class)); + assertEquals(UUID.fromString(uuid), rs.getObject(5, UUID.class)); + assertEquals(UUID.fromString(uuid), rs.getObject("col5", UUID.class)); SQLXML sqlXml; sqlXml = rs.getObject(6, SQLXML.class); @@ -239,7 +243,7 @@ public void testJdbc41ResultSetMethods() throws SQLException { assertFalse(rs.next()); } } finally { - stmt.executeUpdate("drop table " + tableName); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } } @@ -260,10 +264,13 @@ public void testGetObjectAsLocalDateTime() throws SQLException { final String testValueTime = "02:00:00.1234567"; final String testValueDateTime = testValueDate + "T" + testValueTime; - stmt.executeUpdate("CREATE TABLE " + tableName + " (id INT PRIMARY KEY, dt2 DATETIME2)"); - stmt.executeUpdate("INSERT INTO " + tableName + " (id, dt2) VALUES (1, '" + testValueDateTime + "')"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id INT PRIMARY KEY, dt2 DATETIME2)"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id, dt2) VALUES (1, '" + testValueDateTime + "')"); - try (ResultSet rs = stmt.executeQuery("SELECT dt2 FROM " + tableName + " WHERE id=1")) { + try (ResultSet rs = stmt.executeQuery( + "SELECT dt2 FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE id=1")) { rs.next(); LocalDateTime expectedLocalDateTime = LocalDateTime.parse(testValueDateTime); @@ -278,7 +285,7 @@ public void testGetObjectAsLocalDateTime() throws SQLException { LocalTime actualLocalTime = rs.getObject(1, LocalTime.class); assertEquals(expectedLocalTime, actualLocalTime); } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); TimeZone.setDefault(prevTimeZone); } } @@ -293,17 +300,18 @@ public void testGetObjectAsLocalDateTime() throws SQLException { public void testResultSetWrapper() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate( - "create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); - try (ResultSet rs = stmt.executeQuery("select * from " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { assertTrue(rs.isWrapperFor(ResultSet.class)); assertTrue(rs.isWrapperFor(ISQLServerResultSet.class)); assertSame(rs, rs.unwrap(ResultSet.class)); assertSame(rs, rs.unwrap(ISQLServerResultSet.class)); } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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 446ac55d7..15e817a7c 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java @@ -17,11 +17,13 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.ComparisonUtil; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; @@ -34,8 +36,8 @@ public class TVPAllTypes extends AbstractTest { private static Connection conn = null; static Statement stmt = null; - private static String tvpName = "TVPAllTypesTable_char_TVP"; - private static String procedureName = "TVPAllTypesTable_char_SP"; + private static String tvpName; + private static String procedureName; private static DBTable tableSrc = null; private static DBTable tableDest = null; @@ -94,7 +96,7 @@ private void testTVPStoredProcedureResultSet(boolean setSelectMethod, Integer re setupVariation(setSelectMethod, resultSetType, resultSetConcurrency); try (ResultSet rs = stmt.executeQuery("select * from " + tableSrc.getEscapedTableName()); SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) conn - .prepareCall("{call " + procedureName + "(?)}")) { + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}")) { Cstmt.setStructured(1, tvpName, rs); Cstmt.execute(); @@ -139,19 +141,24 @@ public void testTVPDataTable() throws SQLException { } private static void createPreocedure(String procedureName, String destTable) throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + destTable + " SELECT * FROM @InputData" + " END"; + tvpName = RandomUtil.getIdentifier("TVPAllTypesTable_char_TVP"); + procedureName = RandomUtil.getIdentifier("TVPAllTypesTable_char_SP"); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + + destTable + " SELECT * FROM @InputData" + " END"; stmt.execute(sql); } private static void dropTVPS(String tvpName) throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); } - private static void createTVPS(String TVPName, String TVPDefinition) throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + TVPName + " as table (" + TVPDefinition + ");"; + private static void createTVPS(String tvpName, String TVPDefinition) throws SQLException { + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (" + + TVPDefinition + ");"; stmt.executeUpdate(TVPCreateCmd); } @@ -170,8 +177,8 @@ private void setupVariation(boolean setSelectMethod, Integer resultSetType, stmt = conn.createStatement(); } - TestUtils.dropProcedureIfExists(procedureName, stmt); - dropTVPS(tvpName); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); + dropTVPS(AbstractSQLGenerator.escapeIdentifier(tvpName)); try (DBConnection dbConnection = new DBConnection(connectionString); DBStatement dbStmt = dbConnection.createStatement()) { @@ -182,18 +189,18 @@ private void setupVariation(boolean setSelectMethod, Integer resultSetType, dbStmt.createTable(tableSrc); dbStmt.createTable(tableDest); - createTVPS(tvpName, tableSrc.getDefinitionOfColumns()); - createPreocedure(procedureName, tableDest.getEscapedTableName()); + createTVPS(AbstractSQLGenerator.escapeIdentifier(tvpName), tableSrc.getDefinitionOfColumns()); + createPreocedure(AbstractSQLGenerator.escapeIdentifier(procedureName), tableDest.getEscapedTableName()); dbStmt.populateTable(tableSrc); } } private void terminateVariation() throws SQLException { - TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); TestUtils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); TestUtils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); - dropTVPS(tvpName); + dropTVPS(AbstractSQLGenerator.escapeIdentifier(tvpName)); if (null != stmt) { stmt.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 507d31c92..25c626102 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java @@ -20,27 +20,27 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest;; @RunWith(JUnitPlatform.class) public class TVPIssuesTest extends AbstractTest { - static Connection connection = null; - static Statement stmt = null; - private static String tvp_varcharMax = "TVPIssuesTest_varcharMax_TVP"; - private static String spName_varcharMax = "TVPIssuesTest_varcharMax_SP"; - private static String srcTable_varcharMax = "TVPIssuesTest_varcharMax_srcTable"; - private static String desTable_varcharMax = "TVPIssuesTest_varcharMax_destTable"; + private static String tvp_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_TVP"); + private static String spName_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_SP"); + private static String srcTable_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_srcTable"); + private static String desTable_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_destTable"); - private static String tvp_time_6 = "TVPIssuesTest_time_6_TVP"; - private static String srcTable_time_6 = "TVPIssuesTest_time_6_srcTable"; - private static String desTable_time_6 = "TVPIssuesTest_time_6_destTable"; + private static String tvp_time_6 = RandomUtil.getIdentifier("TVPIssuesTest_time_6_TVP"); + private static String srcTable_time_6 = RandomUtil.getIdentifier("TVPIssuesTest_time_6_srcTable"); + private static String desTable_time_6 = RandomUtil.getIdentifier("TVPIssuesTest_time_6_destTable"); private static String expectedTime6value = "15:39:27.616667"; @@ -49,10 +49,12 @@ public void tryTVPRSvarcharMax4000Issue() throws Exception { setup(); try (SQLServerStatement st = (SQLServerStatement) connection.createStatement(); - ResultSet rs = st.executeQuery("select * from " + srcTable_varcharMax); + ResultSet rs = st + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax)); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + desTable_varcharMax + " select * from ? ;")) { + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax) + + " select * from ? ;")) { pstmt.setStructured(1, tvp_varcharMax, rs); pstmt.execute(); @@ -69,11 +71,11 @@ public void tryTVPRSvarcharMax4000Issue() throws Exception { @Test public void testExceptionWithInvalidStoredProcedureName() throws Exception { SQLServerStatement st = (SQLServerStatement) connection.createStatement(); - ResultSet rs = st.executeQuery("select * from " + srcTable_varcharMax); + ResultSet rs = st.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax)); dropProcedure(); - final String sql = "{call " + spName_varcharMax + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(spName_varcharMax) + "(?)}"; try (SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) connection.prepareCall(sql)) { Cstmt.setObject(1, rs); @@ -98,9 +100,13 @@ public void testExceptionWithInvalidStoredProcedureName() throws Exception { public void tryTVPPrecisionmissedissue315() throws Exception { setup(); - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable_time_6); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement(); + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6)); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + desTable_time_6 + " select * from ? ;")) { + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable_time_6) + + " select * from ? ;")) { pstmt.setStructured(1, tvp_time_6, rs); pstmt.execute(); @@ -109,7 +115,8 @@ public void tryTVPPrecisionmissedissue315() throws Exception { } private void testCharDestTable() throws SQLException, IOException { - try (ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_varcharMax)) { + try (ResultSet rs = connection.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax))) { while (rs.next()) { assertEquals(rs.getString(1).length(), 4001, TestResource.getResource("R_lengthTruncated")); } @@ -117,7 +124,8 @@ private void testCharDestTable() throws SQLException, IOException { } private void testTime6DestTable() throws SQLException, IOException { - try (ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_time_6)) { + try (ResultSet rs = connection.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable_time_6))) { while (rs.next()) { assertEquals(rs.getString(1), expectedTime6value, TestResource.getResource("R_timeValueTruncated")); } @@ -126,45 +134,52 @@ private void testTime6DestTable() throws SQLException, IOException { @BeforeAll public static void beforeAll() throws SQLException { - connection = DriverManager.getConnection(connectionString); - stmt = connection.createStatement(); - - dropProcedure(); - - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_varcharMax - + "') " + " drop type " + tvp_varcharMax); - 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); - 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); - sql = "create table " + desTable_varcharMax + " (c1 varchar(max) null);"; - stmt.execute(sql); - - sql = "create table " + srcTable_time_6 + " (c1 time(6) null);"; - stmt.execute(sql); - sql = "create table " + desTable_time_6 + " (c1 time(6) null);"; - stmt.execute(sql); - - String TVPCreateCmd = "CREATE TYPE " + tvp_varcharMax + " as table (c1 varchar(max) null)"; - stmt.executeUpdate(TVPCreateCmd); - - TVPCreateCmd = "CREATE TYPE " + tvp_time_6 + " as table (c1 time(6) null)"; - stmt.executeUpdate(TVPCreateCmd); - - createPreocedure(); - - populateCharSrcTable(); - populateTime6SrcTable(); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + + dropProcedure(); + + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_varcharMax) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax), stmt); + + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_time_6) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_time_6)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_time_6), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_time_6), stmt); + + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax) + + " (c1 varchar(max) null);"; + stmt.execute(sql); + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax) + + " (c1 varchar(max) null);"; + stmt.execute(sql); + + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6) + " (c1 time(6) null);"; + stmt.execute(sql); + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable_time_6) + " (c1 time(6) null);"; + stmt.execute(sql); + + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax) + + " as table (c1 varchar(max) null)"; + stmt.executeUpdate(TVPCreateCmd); + + TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvp_time_6) + + " as table (c1 time(6) null)"; + stmt.executeUpdate(TVPCreateCmd); + + createProcedure(); + + populateCharSrcTable(); + populateTime6SrcTable(); + } } private static void populateCharSrcTable() throws SQLException { - String sql = "insert into " + srcTable_varcharMax + " values (?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax) + " values (?)"; StringBuffer sb = new StringBuffer(); for (int i = 0; i < 4001; i++) { @@ -180,40 +195,49 @@ private static void populateCharSrcTable() throws SQLException { } private static void populateTime6SrcTable() throws SQLException { - String sql = "insert into " + srcTable_time_6 + " values ('2017-05-12 " + expectedTime6value + "')"; - connection.createStatement().execute(sql); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6) + + " values ('2017-05-12 " + expectedTime6value + "')"; + connection.createStatement().execute(sql); + } } private static void dropProcedure() throws SQLException { - TestUtils.dropProcedureIfExists(spName_varcharMax, stmt); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(spName_varcharMax), stmt); + } } - private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + spName_varcharMax + " @InputData " + tvp_varcharMax + " READONLY " + " AS " - + " BEGIN " + " INSERT INTO " + desTable_varcharMax + " SELECT * FROM @InputData" + " END"; + private static void createProcedure() throws SQLException { + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(spName_varcharMax) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax) + " READONLY " + " AS " + " BEGIN " + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax) + + " SELECT * FROM @InputData" + " END"; - stmt.execute(sql); + stmt.execute(sql); + } } @AfterAll 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); - 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); - TestUtils.dropTableIfExists(srcTable_time_6, stmt); - TestUtils.dropTableIfExists(desTable_time_6, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != connection) { - connection.close(); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_varcharMax) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax), stmt); + + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_time_6) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_time_6)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_time_6), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_time_6), stmt); } } } 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 1cfbeedc9..0cde14730 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java @@ -6,6 +6,9 @@ import java.sql.SQLException; import java.sql.SQLTimeoutException; +import java.sql.Connection; +import java.sql.Statement; +import java.sql.DriverManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -13,27 +16,24 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; +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.DBResultSet; -import com.microsoft.sqlserver.testframework.DBStatement; @RunWith(JUnitPlatform.class) public class TVPNumericTest extends AbstractTest { - private static DBConnection conn = null; - static DBStatement stmt = null; - static DBResultSet rs = null; static SQLServerDataTable tvp = null; static String expectecValue1 = "hello"; static String expectecValue2 = "world"; static String expectecValue3 = "again"; - private static String tvpName = "numericTVP"; - private static String charTable = "tvpNumericTable"; - private static String procedureName = "procedureThatCallsTVP"; + private static String tvpName; + private static String charTable; + private static String procedureName; /** * Test a previous failure regarding to numeric precision. Issue #211 @@ -49,8 +49,8 @@ public void testNumericPresicionIssue211() throws SQLException { tvp.addRow(12.12); tvp.addRow(1.123); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + charTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(charTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -59,8 +59,9 @@ public void testNumericPresicionIssue211() throws SQLException { @BeforeEach public void testSetup() throws SQLException { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); + tvpName = RandomUtil.getIdentifier("numericTVP"); + procedureName = RandomUtil.getIdentifier("procedureThatCallsTVP"); + charTable = RandomUtil.getIdentifier("tvpNumericTable"); dropProcedure(); dropTables(); @@ -72,48 +73,59 @@ public void testSetup() throws SQLException { } private 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'" + + TestUtils.escapeSingleQuotes(procedureName) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName); + stmt.execute(sql); + } } private static void dropTables() throws SQLException { - stmt.executeUpdate("if object_id('" + charTable + "','U') is not null" + " drop table " + charTable); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(charTable) + "','U') is not null" + + " drop table " + AbstractSQLGenerator.escapeIdentifier(charTable)); + } } 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 = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); + } } private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + charTable + " SELECT * FROM @InputData" + " END"; - - stmt.execute(sql); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " SELECT * FROM @InputData" + " END"; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTables() throws SQLException { - String sql = "create table " + charTable + " (c1 numeric(6,3) null);"; - stmt.execute(sql); + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (c1 numeric(6,3) null);"; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTVPS() throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 numeric(6,3) null)"; - stmt.executeUpdate(TVPCreateCmd); + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + + " as table (c1 numeric(6,3) null)"; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate(TVPCreateCmd); + } } @AfterEach public void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } + dropProcedure(); + dropTables(); + dropTVPS(); + if (null != tvp) { tvp.clear(); } 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 0c522fdbd..60f0223fe 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java @@ -17,14 +17,17 @@ import java.util.Properties; import java.util.TimeZone; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -42,10 +45,10 @@ public class TVPResultSetCursorTest 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 tvpName = "TVPResultSetCursorTest_TVP"; - private static String procedureName = "TVPResultSetCursorTest_SP"; - private static String srcTable = "TVPResultSetCursorTest_SourceTable"; - private static String desTable = "TVPResultSetCursorTest_DestinationTable"; + private static String tvpName = RandomUtil.getIdentifier("TVPResultSetCursorTest_TVP"); + private static String procedureName = RandomUtil.getIdentifier("TVPResultSetCursorTest_SP"); + private static String srcTable = RandomUtil.getIdentifier("TVPResultSetCursorTest_SourceTable"); + private static String desTable = RandomUtil.getIdentifier("TVPResultSetCursorTest_DestinationTable"); /** * Test a previous failure when using server cursor and using the same connection to create TVP and result set. @@ -72,10 +75,10 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro 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); + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length); @@ -104,10 +107,11 @@ public void testSelectMethodSetToCursor() throws SQLException { 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); + try (ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length); @@ -134,14 +138,15 @@ public void testSelectMethodSetToCursorWithSP() throws SQLException { createTVPS(); createTables(); - createPreocedure(); + createProcedure(); populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + try (ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn - .prepareCall("{call " + procedureName + "(?)}")) { - pstmt.setStructured(1, tvpName, rs); + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); @@ -172,9 +177,10 @@ public void testInvalidTVPName() throws SQLException { 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 " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { pstmt.setStructured(1, "invalid" + tvpName, rs); @@ -205,13 +211,14 @@ public void testInvalidStoredProcedureName() throws SQLException { createTVPS(); createTables(); - createPreocedure(); + createProcedure(); populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn - .prepareCall("{call invalid" + procedureName + "(?)}")) { + try (ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn.prepareCall( + "{call invalid" + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}")) { pstmt.setStructured(1, tvpName, rs); pstmt.execute(); @@ -244,34 +251,35 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { populateSourceTable(); try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable)) { + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable))) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(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); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(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); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length * 3); } - String sql = "insert into " + desTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(desTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { for (int i = 0; i < expectedBigDecimals.length; i++) { @@ -284,10 +292,12 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { verifyDestinationTableData(expectedBigDecimals.length * 4); } } - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable); + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length * 5); } @@ -297,7 +307,8 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); - ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable))) { int expectedArrayLength = expectedBigDecimals.length; @@ -319,7 +330,7 @@ private static void verifyDestinationTableData(int expectedNumberOfRows) throws } private static void populateSourceTable() throws SQLException { - String sql = "insert into " + srcTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); @@ -338,18 +349,18 @@ private static void populateSourceTable() throws SQLException { private static void dropTables() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - TestUtils.dropTableIfExists(srcTable, stmt); - TestUtils.dropTableIfExists(desTable, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable), stmt); } } private static void createTables() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String sql = "create table " + srcTable + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); - sql = "create table " + desTable + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } @@ -357,7 +368,7 @@ private static void createTables() throws SQLException { private static void createTVPS() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String TVPCreateCmd = "CREATE TYPE " + tvpName + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000) null)"; stmt.execute(TVPCreateCmd); } @@ -365,23 +376,33 @@ private static void createTVPS() throws SQLException { private static void dropTVPS() throws SQLException { 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); + stmt.execute("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); } } private static void dropProcedure() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); } } - private static void createPreocedure() throws SQLException { + private static void createProcedure() throws SQLException { 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"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " SELECT * FROM @InputData" + + " END"; stmt.execute(sql); } } + + @AfterAll + public static void terminate() throws SQLException { + dropProcedure(); + dropTVPS(); + dropTables(); + } } 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 4abf1bc12..a375fe044 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java @@ -7,7 +7,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.Statement; +import java.sql.ResultSet; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -16,30 +20,27 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; +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.DBResultSet; -import com.microsoft.sqlserver.testframework.DBStatement; @RunWith(JUnitPlatform.class) public class TVPSchemaTest extends AbstractTest { - private static DBConnection conn = null; - static DBStatement stmt = null; - static DBResultSet rs = null; static SQLServerDataTable tvp = null; static String expectecValue1 = "hello"; static String expectecValue2 = "world"; static String expectecValue3 = "again"; - private static String schemaName = "anotherSchma"; - private static String tvpNameWithouSchema = "charTVP"; - private static String tvpNameWithSchema = "[" + schemaName + "].[" + tvpNameWithouSchema + "]"; - private static String charTable = "[" + schemaName + "].[tvpCharTable]"; - private static String procedureName = "[" + schemaName + "].[procedureThatCallsTVP]"; + private static String schemaName; + private static String tvpNameWithouSchema; + private static String tvpNameWithSchema; + private static String charTable; + private static String procedureName; /** * PreparedStatement with storedProcedure @@ -52,12 +53,14 @@ public void testTVPSchemaPreparedStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - try (SQLServerPreparedStatement P_C_statement = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerPreparedStatement P_C_statement = (SQLServerPreparedStatement) conn.prepareStatement(sql); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_statement.setStructured(1, tvpNameWithSchema, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); + } } @@ -72,11 +75,12 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) conn.prepareCall(sql); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_statement.setStructured(1, tvpNameWithSchema, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); } } @@ -91,12 +95,13 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException @DisplayName("TVPSchemaPreparedInsertCommand") public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOException { - try (SQLServerPreparedStatement P_C_stmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + charTable + " select * from ? ;")) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerPreparedStatement P_C_stmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + charTable + " select * from ? ;"); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); P_C_stmt.executeUpdate(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); } } @@ -111,20 +116,28 @@ public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOExceptio @DisplayName("TVPSchemaCallableInsertCommand()") public void testTVPSchemaCallableInsertCommand() throws SQLException, IOException { - try (SQLServerCallableStatement P_C_stmt = (SQLServerCallableStatement) connection - .prepareCall("INSERT INTO " + charTable + " select * from ? ;")) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerCallableStatement P_C_stmt = (SQLServerCallableStatement) conn + .prepareCall("INSERT INTO " + charTable + " select * from ? ;"); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); P_C_stmt.executeUpdate(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); } } @BeforeEach public void testSetup() throws SQLException { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); + schemaName = RandomUtil.getIdentifier("anotherSchema"); + tvpNameWithouSchema = RandomUtil.getIdentifier("charTVP"); + tvpNameWithSchema = AbstractSQLGenerator.escapeIdentifier(schemaName) + "." + + AbstractSQLGenerator.escapeIdentifier(tvpNameWithouSchema); + + charTable = AbstractSQLGenerator.escapeIdentifier(schemaName) + "." + + AbstractSQLGenerator.escapeIdentifier("tvpCharTable"); + procedureName = AbstractSQLGenerator.escapeIdentifier(schemaName) + "." + + AbstractSQLGenerator.escapeIdentifier("procedureThatCallsTVP"); dropProcedure(); dropTables(); @@ -148,7 +161,7 @@ public void testSetup() throws SQLException { tvp.addRow(expectecValue1, expectecValue2, expectecValue3); } - private void verify(DBResultSet rs) throws SQLException { + private void verify(ResultSet rs) throws SQLException { while (rs.next()) { String actualValue1 = rs.getString(1); String actualValue2 = rs.getString(2); @@ -161,58 +174,71 @@ private void verify(DBResultSet rs) throws SQLException { } private 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); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(procedureName) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + procedureName; + + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private static void dropTables() throws SQLException { - stmt.executeUpdate("if object_id('" + charTable + "','U') is not null" + " drop table " + charTable); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(charTable) + "','U') is not null" + + " drop table " + charTable); + } } private static void dropTVPS() throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" - + tvpNameWithouSchema + "') " + " drop type " + tvpNameWithSchema); + 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 = '" + + TestUtils.escapeSingleQuotes(tvpNameWithouSchema) + "') " + " drop type " + tvpNameWithSchema); + } } private static void dropAndCreateSchema() throws SQLException { - stmt.execute("if EXISTS (SELECT * FROM sys.schemas where name = 'anotherSchma') drop schema anotherSchma"); - stmt.execute("CREATE SCHEMA anotherSchma"); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute( + "if EXISTS (SELECT * FROM sys.schemas where name = '" + TestUtils.escapeSingleQuotes(schemaName) + + "') drop schema " + AbstractSQLGenerator.escapeIdentifier(schemaName)); + stmt.execute("CREATE SCHEMA " + AbstractSQLGenerator.escapeIdentifier(schemaName)); + } } private static void createPreocedure() throws SQLException { String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpNameWithSchema + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + charTable + " SELECT * FROM @InputData" + " END"; - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTables() throws SQLException { String sql = "create table " + charTable + " (" + "PlainChar char(50) null," + "PlainVarchar varchar(50) null," + "PlainVarcharMax varchar(max) null," + ");"; - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTVPS() throws SQLException { String TVPCreateCmd = "CREATE TYPE " + tvpNameWithSchema + " as table ( " + "PlainChar char(50) null," + "PlainVarchar varchar(50) null," + "PlainVarcharMax varchar(max) null" + ")"; - stmt.executeUpdate(TVPCreateCmd); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate(TVPCreateCmd); + } } @AfterEach public void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } + dropProcedure(); + dropTables(); + dropTVPS(); + if (null != tvp) { tvp.clear(); } } - } 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 260c13974..d48f3bb57 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java @@ -21,10 +21,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -32,9 +35,9 @@ public class TVPTypesTest extends AbstractTest { static SQLServerDataTable tvp = null; - private static String tvpName = "TVP"; - private static String table = "TVPTable"; - private static String procedureName = "procedureThatCallsTVP"; + private static String tvpName; + private static String tableName; + private static String procedureName; private String value = null; /** @@ -56,14 +59,15 @@ public void testLongVarchar() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -90,15 +94,15 @@ public void testLongNVarchar() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + Statement stmt = conn.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -123,14 +127,15 @@ public void testXML() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.SQLXML); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -154,14 +159,15 @@ public void testnText() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -185,14 +191,15 @@ public void testText() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -216,14 +223,15 @@ public void testImage() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARBINARY); tvp.addRow(value.getBytes()); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertTrue(parseByte(rs.getBytes(1), value.getBytes())); @@ -251,14 +259,15 @@ public void testTVPLongVarcharStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -284,14 +293,15 @@ public void testTVPLongNVarcharStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(buffer.toString()); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -317,14 +327,15 @@ public void testTVPXMLStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.SQLXML); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -351,14 +362,15 @@ public void testTVPTextStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -385,14 +397,15 @@ public void testTVPNTextStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -419,14 +432,15 @@ public void testTVPImageStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARBINARY); tvp.addRow(value.getBytes()); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertTrue(parseByte(rs.getBytes(1), value.getBytes())); } @@ -449,14 +463,15 @@ public void testDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.DATETIME); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(((SQLServerResultSet) rs).getDateTime(1), value); } @@ -481,14 +496,15 @@ public void testSmallDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SMALLDATETIME); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(((SQLServerResultSet) rs).getSmallDateTime(1), returnValue); } @@ -498,6 +514,10 @@ public void testSmallDateTime() throws SQLException { @BeforeEach public void testSetup() throws SQLException { + tvpName = RandomUtil.getIdentifier("TVP"); + tableName = RandomUtil.getIdentifier("TVPTable"); + procedureName = RandomUtil.getIdentifier("procedureThatCallsTVP"); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { dropProcedure(); dropTables(); @@ -516,43 +536,50 @@ public static void terminate() throws SQLException { private static void dropProcedure() throws SQLException { 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; + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(procedureName) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName); stmt.execute(sql); } } private static void dropTables() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - stmt.executeUpdate("if object_id('" + table + "','U') is not null" + " drop table " + table); + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(tableName) + "','U') is not null" + + " drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } private static void dropTVPS() throws SQLException { 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); + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); } } private static void createPreocedure() throws SQLException { 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"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SELECT * FROM @InputData" + + " END"; stmt.execute(sql); } } private void createTables(String colType) throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String sql = "create table " + table + " (c1 " + colType + " null);"; + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1 " + colType + + " null);"; stmt.execute(sql); } } private void createTVPS(String colType) throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 " + colType + " null)"; + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 " + + colType + " null)"; stmt.executeUpdate(TVPCreateCmd); } } @@ -568,6 +595,10 @@ private boolean parseByte(byte[] expectedData, byte[] retrieved) { @AfterEach public void terminateVariation() throws SQLException { + dropProcedure(); + dropTables(); + dropTVPS(); + 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 df8214b3e..228785659 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java @@ -110,7 +110,7 @@ public static void setUp() throws ClassNotFoundException, SQLException { connection = PrepUtil.getConnection(getConfiguredProperty("mssql_jdbc_test_connection_properties")); if (TestUtils.serverSupportsUTF8(connection)) { databaseName = RandomUtil.getIdentifier("UTF8Database"); - tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundaryTable")); + tableName = RandomUtil.getIdentifier("RequestBoundaryTable"); createDatabaseWithUTF8Collation(); connection.setCatalog(databaseName); } @@ -137,20 +137,23 @@ private static void createDatabaseWithUTF8Collation() throws SQLException { private static void createTable(String columnType) throws SQLException { try (Statement stmt = connection.createStatement();) { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("CREATE TABLE " + tableName + " (c " + columnType + ")"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c " + columnType + ")"); } } public void clearTable() throws SQLException { try (Statement stmt = connection.createStatement();) { - stmt.executeUpdate("DELETE FROM " + tableName); + stmt.executeUpdate("DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } public void validate(String value) throws SQLException { - try (PreparedStatement psInsert = connection.prepareStatement("INSERT INTO " + tableName + " VALUES(?)"); - PreparedStatement psFetch = connection.prepareStatement("SELECT * FROM " + tableName); + try (PreparedStatement psInsert = connection + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES(?)"); + PreparedStatement psFetch = connection + .prepareStatement("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName)); Statement stmt = connection.createStatement();) { clearTable(); // Used for exact byte comparison. @@ -160,7 +163,8 @@ public void validate(String value) throws SQLException { psInsert.executeUpdate(); // Fetch using Statement. - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); // Compare Strings. assertEquals(value, rs.getString(1)); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java index 55e8e1576..f537c1657 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java @@ -26,6 +26,7 @@ import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -81,7 +82,8 @@ private String getStringFromReader(Reader r, long l) throws IOException { private void createLobTable(Statement stmt, String table, Lob l) throws SQLException { String columnType = (l == Lob.CLOB) ? "varchar(max)" : "nvarchar(max)"; - stmt.execute("CREATE TABLE [" + table + "] (id int, lobValue " + columnType + ")"); + stmt.execute("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table) + " (id int, lobValue " + columnType + + ")"); } private ArrayList createRandomStringArray(Lob l) { 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 68cd41d7b..628e09a71 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 @@ -323,23 +323,20 @@ private void testMultipleClose(Class streamClass) throws Exception { continue; } - 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 { - // close the stream twice - if (streamClass == DBCharacterStream.class) { - ((Reader) stream).close(); - ((Reader) stream).close(); - } else { - ((InputStream) stream).close(); - ((InputStream) stream).close(); + if (streamClass == DBCharacterStream.class) { + try (Reader stream = (Reader) rs.getXXX(i + 1, streamClass)) { + if (null == stream) { + assertEquals(stream, rs.getObject(i + 1), + TestResource.getResource("R_streamNull")); + } + } + } else { + try (InputStream stream = (InputStream) rs.getXXX(i + 1, streamClass)) { + if (null == stream) { + assertEquals(stream, rs.getObject(i + 1), + TestResource.getResource("R_streamNull")); } } - } } } @@ -589,6 +586,7 @@ public void readMultipleBlobStreamsThenCloseRS() throws Exception { if (null != stream) { stream.close(); } + dropTables(table); } } 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 53b885651..7d14a67ab 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 @@ -44,12 +44,13 @@ public class BatchExecuteWithErrorsTest extends AbstractTest { public static final Logger log = Logger.getLogger("BatchExecuteWithErrors"); Connection con = null; - String tableN = RandomUtil.getIdentifier("t_Repro47239"); - final String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); - final String insertStmt = "INSERT INTO " + tableName + " VALUES (999, 'HELLO', '4/12/1994')"; + final String tableName = RandomUtil.getIdentifier("t_Repro47239"); + final String insertStmt = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (999, 'HELLO', '4/12/1994')"; final String error16 = "RAISERROR ('raiserror level 16',16,42)"; final String select = "SELECT 1"; - final String dateConversionError = "insert into " + tableName + " values (999999, 'Hello again', 'asdfasdf')"; + final String dateConversionError = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " values (999999, 'Hello again', 'asdfasdf')"; /** * Batch test @@ -86,12 +87,13 @@ public void Repro47239largeUseBulkCopyAPI() throws Exception { } private void Repro47239Internal(String mode) throws Exception { - String tableN = RandomUtil.getIdentifier("t_Repro47239"); - final String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); - final String insertStmt = "INSERT INTO " + tableName + " VALUES (999, 'HELLO', '4/12/1994')"; + final String tableName = RandomUtil.getIdentifier("t_Repro47239"); + final String insertStmt = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (999, 'HELLO', '4/12/1994')"; final String error16 = "RAISERROR ('raiserror level 16',16,42)"; final String select = "SELECT 1"; - final String dateConversionError = "insert into " + tableName + " values (999999, 'Hello again', 'asdfasdf')"; + final String dateConversionError = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " values (999999, 'Hello again', 'asdfasdf')"; String warning; String error; @@ -139,9 +141,9 @@ private void Repro47239Internal(String mode) throws Exception { try (Statement stmt = conn.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (Exception ignored) {} - stmt.executeUpdate("create table " + tableName + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1_int int, c2_varchar varchar(20), c3_date datetime, c4_int int identity(1,1) primary key)"); // Regular Statement batch update @@ -299,7 +301,7 @@ private void Repro47239Internal(String mode) throws Exception { } finally { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - stmt.executeUpdate("drop table " + tableName); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } } @@ -352,10 +354,10 @@ private void Repro47239largeInternal(String mode) throws Exception { try (Statement stmt = conn.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (Exception ignored) {} try { - stmt.executeLargeUpdate("create table " + tableName + stmt.executeLargeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(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 @@ -505,7 +507,7 @@ private void Repro47239largeInternal(String mode) throws Exception { } try { - stmt.executeLargeUpdate("drop table " + tableName); + stmt.executeLargeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } catch (Exception ignored) {} } } 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 aeaecf6c7..66375ec46 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 @@ -23,10 +23,12 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +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.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; @@ -38,6 +40,9 @@ @RunWith(JUnitPlatform.class) public class BatchExecutionTest extends AbstractTest { + static String ctstable1; + static String ctstable2; + /** * 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 @@ -82,7 +87,8 @@ private void testExecuteBatch1Internal(String mode) { int updateCountlen = 0; try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { - String sPrepStmt = "update ctstable2 set PRICE=PRICE*20 where TYPE_ID=?"; + String sPrepStmt = "update " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " set PRICE=PRICE*20 where TYPE_ID=?"; if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI((SQLServerConnection) connection); @@ -105,7 +111,8 @@ private void testExecuteBatch1Internal(String mode) { assertTrue(updateCountlen == 3, TestResource.getResource("R_executeBatchFailed") + ": " + TestResource.getResource("R_incorrectUpdateCount")); - String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; + String sPrepStmt1 = "select count(*) from " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " where TYPE_ID=?"; try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1)) { for (int n = 1; n <= 3; n++) { @@ -133,23 +140,30 @@ private static void createTable() throws SQLException { 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) "; + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + + " (TYPE_ID int, TYPE_DESC varchar(32), primary key(TYPE_ID)) "; + String sql2 = "create table " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " (KEY_ID int, COF_NAME varchar(32), PRICE float, TYPE_ID int, primary key(KEY_ID), foreign key(TYPE_ID) references " + + AbstractSQLGenerator.escapeIdentifier(ctstable1) + ")"; stmt.execute(sql1); stmt.execute(sql2); - String sqlin2 = "insert into ctstable1 values (1,'COFFEE-Desc')"; + String sqlin2 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + + " values (1,'COFFEE-Desc')"; stmt.execute(sqlin2); - sqlin2 = "insert into ctstable1 values (2,'COFFEE-Desc2')"; + sqlin2 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + " values (2,'COFFEE-Desc2')"; stmt.execute(sqlin2); - sqlin2 = "insert into ctstable1 values (3,'COFFEE-Desc3')"; + sqlin2 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + " values (3,'COFFEE-Desc3')"; stmt.execute(sqlin2); - String sqlin1 = "insert into ctstable2 values (9,'COFFEE-9',9.0, 1)"; + String sqlin1 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " values (9,'COFFEE-9',9.0, 1)"; stmt.execute(sqlin1); - sqlin1 = "insert into ctstable2 values (10,'COFFEE-10',10.0, 2)"; + sqlin1 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " values (10,'COFFEE-10',10.0, 2)"; stmt.execute(sqlin1); - sqlin1 = "insert into ctstable2 values (11,'COFFEE-11',11.0, 3)"; + sqlin1 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " values (11,'COFFEE-11',11.0, 3)"; stmt.execute(sqlin1); } } @@ -159,7 +173,8 @@ private void testAddBatch1Internal(String mode) { int retValue[] = {0, 0, 0}; try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { - String sPrepStmt = "update ctstable2 set PRICE=PRICE*20 where TYPE_ID=?"; + String sPrepStmt = "update " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " set PRICE=PRICE*20 where TYPE_ID=?"; if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI((SQLServerConnection) connection); @@ -181,7 +196,8 @@ private void testAddBatch1Internal(String mode) { 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 " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " where TYPE_ID=?"; try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1)) { @@ -217,6 +233,9 @@ private void modifyConnectionForBulkCopyAPI(SQLServerConnection con) throws Exce @BeforeAll public static void testSetup() throws TestAbortedException, Exception { + ctstable1 = RandomUtil.getIdentifier("ctstable1"); + ctstable2 = RandomUtil.getIdentifier("ctstable2"); + try (DBConnection con = new DBConnection(connectionString)) { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } @@ -229,8 +248,8 @@ private static void dropTable() throws SQLException { try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists("ctstable2", stmt); - TestUtils.dropTableIfExists("ctstable1", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(ctstable2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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 60d279cf2..897c9ade3 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 @@ -20,9 +20,11 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomUtil; 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; @@ -33,10 +35,9 @@ @RunWith(JUnitPlatform.class) public class BatchTriggerTest extends AbstractTest { - static String tableName = "triggerTable"; - static String triggerName = "triggerTest"; - static String insertQuery = "insert into " + tableName - + " (col1, col2, col3, col4) values (1, '22-08-2017 17:30:00.000', 'R4760', 31)"; + static String tableName; + static String triggerName;; + static String insertQuery; /** * Tests that the proper trigger exception is thrown using statement @@ -83,9 +84,11 @@ public void preparedStatementTest() throws SQLException { private static void createTrigger(String triggerName) throws SQLException { 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"; + String sql = "create trigger " + triggerName + " on " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " for insert " + "as " + "begin " + "if (select col1 from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + ") > 10 " + "begin " + "return " + "end " + + "RAISERROR ('" + TestResource.getResource("R_customErrorMessage") + "', 16, 0) " + + "rollback transaction " + "end"; stmt.execute(sql); } } @@ -98,7 +101,8 @@ private static void createTrigger(String triggerName) throws SQLException { private static void createTable() throws SQLException { 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)"; + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ( col1 int, col2 varchar(50), col3 varchar(10), col4 int)"; stmt.execute(sql); } } @@ -111,14 +115,19 @@ private static void createTable() throws SQLException { */ @BeforeAll public static void testSetup() throws TestAbortedException, Exception { + tableName = RandomUtil.getIdentifier("triggerTable"); + triggerName = RandomUtil.getIdentifier("triggerTest"); + insertQuery = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1, col2, col3, col4) values (1, '22-08-2017 17:30:00.000', 'R4760', 31)"; + 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 + ";"); + + " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n" + + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + ";"); dropTable(); createTable(); - createTrigger(triggerName); + createTrigger(AbstractSQLGenerator.escapeIdentifier(triggerName)); } } @@ -130,7 +139,7 @@ public static void testSetup() throws TestAbortedException, Exception { private static void dropTable() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } @@ -146,8 +155,8 @@ 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 + ";"); + + " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n" + + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + ";"); } } } 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 1aa0e28a1..ee98c17dc 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,10 +31,8 @@ */ @RunWith(JUnitPlatform.class) public class CallableMixedTest extends AbstractTest { - String tableN = RandomUtil.getIdentifier("TFOO3"); - String procN = RandomUtil.getIdentifier("SPFOO3"); - String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); - String procName = AbstractSQLGenerator.escapeIdentifier(procN); + String tableName = RandomUtil.getIdentifier("TFOO3"); + String procName = RandomUtil.getIdentifier("SPFOO3"); /** * Tests Callable mix @@ -47,16 +45,18 @@ public void datatypesTest() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement();) { - statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); - statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); + statement.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (c1_int int primary key, col2 int)"); + statement + .executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 1)"); - statement.executeUpdate("CREATE PROCEDURE " + procName + statement.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " - + tableName + + AbstractSQLGenerator.escapeIdentifier(tableName) + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - try (CallableStatement callableStatement = connection - .prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }")) { + try (CallableStatement callableStatement = connection.prepareCall( + "{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?, ?, ?, ?) }")) { callableStatement.registerOutParameter((int) 1, (int) 4); callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); callableStatement.registerOutParameter((int) 3, (int) 4); @@ -104,7 +104,7 @@ public void datatypesTest() throws SQLException { * @throws SQLException */ private void terminateVariation(Statement statement) throws SQLException { - TestUtils.dropTableIfExists(tableName, statement); - TestUtils.dropProcedureIfExists(procName, statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), statement); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(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 e94d42d2a..98f403913 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 @@ -27,8 +27,10 @@ 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; @@ -42,6 +44,13 @@ public class LimitEscapeTest extends AbstractTest { private static Vector offsetQuery = new Vector<>(); private static Connection conn = null; + // TODO: remove quote for now to avoid bug in driver + static String table1 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t1").replaceAll("\'", ""); + static String table2 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t2").replaceAll("\'", ""); + static String table3 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t3").replaceAll("\'", ""); + static String table4 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t4").replaceAll("\'", ""); + static String procName = RandomUtil.getIdentifier("UnitStatement_LimitEscape_p1").replaceAll("\'", ""); + static class Query { String inputSql, outputSql; int[] idCols = null; @@ -214,38 +223,45 @@ public static void createAndPopulateTables(Connection conn) throws Exception { // is done // around table names. try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t1"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table1)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t2"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table2)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t3"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table3)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t4"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table4)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop procedure UnitStatement_LimitEscape_p1"); + stmt.executeUpdate("drop procedure " + AbstractSQLGenerator.escapeIdentifier(procName)); } 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'), " + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table1) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table2) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table3) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table4) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table1) + " 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.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table2) + + " values (11, 11, 'col33', 'col44')"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table3) + + " values (111, 111, 'col333', 'col444')"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table4) + + " values (1111, 1111, 'col4444', 'col4444')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value varchar(512), @col4Value varchar(512) AS BEGIN SELECT TOP 1 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = @col3Value and col4 = @col4Value END"; stmt.execute(query); } } @@ -261,8 +277,8 @@ public void initAndVerifyQueries() throws Exception { Query qry; // 1 // Test whether queries without limit syntax works - qry = new Query("select TOP 1 * from UnitStatement_LimitEscape_t1", - "select TOP 1 * from UnitStatement_LimitEscape_t1", 1, // # of rows + qry = new Query("select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1), + "select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -271,8 +287,8 @@ public void initAndVerifyQueries() throws Exception { // 2 // Test parentheses in limit syntax - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit ( ( (2)))}", - "select TOP ( ( (2))) * from UnitStatement_LimitEscape_t1", 2, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit ( ( (2)))}", + "select TOP ( ( (2))) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 2, // # of rows 5, // # of columns new int[] {1, 2}, // id column values new int[][] {{1, 1}, {2, 2}}, // int column values @@ -283,9 +299,10 @@ public void initAndVerifyQueries() throws Exception { // 3 // Test limit syntax in string literal as well as in query, also test subquery syntax in string literal - qry = new Query( - "select ( (col1)), ( ((col2) ) ) from UnitStatement_LimitEscape_t1 where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})' {limit (35)}", - "select TOP (35) ( (col1)), ( ((col2) ) ) from UnitStatement_LimitEscape_t1 where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})'", + qry = new Query("select ( (col1)), ( ((col2) ) ) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})' {limit (35)}", + "select TOP (35) ( (col1)), ( ((col2) ) ) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})'", 1, // # of rows 2, // # of columns new int[] {3}, // id column values @@ -295,9 +312,10 @@ public void initAndVerifyQueries() throws Exception { // 4 // Test quotes/limit syntax/scalar function in string literal. Also test real limit syntax in query. - qry = new Query( - "select (col1), (col2) from UnitStatement_LimitEscape_t1 where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)' {limit 3543}", - "select TOP 3543 (col1), (col2) from UnitStatement_LimitEscape_t1 where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)'", + qry = new Query("select (col1), (col2) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)' {limit 3543}", + "select TOP 3543 (col1), (col2) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)'", 1, // # of rows 2, // # of columns new int[] {4}, // id column values @@ -307,9 +325,10 @@ public void initAndVerifyQueries() throws Exception { // 5 // Test openquery/openrowset in string literals - qry = new Query( - "select col1 from UnitStatement_LimitEscape_t1 where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')' {limit (((2)))}", - "select TOP (((2))) col1 from UnitStatement_LimitEscape_t1 where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')'", + qry = new Query("select col1 from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')' {limit (((2)))}", + "select TOP (((2))) col1 from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')'", 1, // # of rows 1, // # of columns new int[] {5}, // id column values @@ -319,8 +338,12 @@ public void initAndVerifyQueries() throws Exception { // 6 // Test limit syntax in subquery as well as in outer query - qry = new Query("select id from (select * from UnitStatement_LimitEscape_t1 {limit 10}) t1 {limit ((1) )}", - "select TOP ((1) ) id from (select TOP 10 * from UnitStatement_LimitEscape_t1) t1", 1, // # of rows + qry = new Query( + "select id from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 10}) t1 {limit ((1) )}", + "select TOP ((1) ) id from (select TOP 10 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ") t1", + 1, // # of rows 1, // # of columns new int[] {1}, // id column values null, // int column values @@ -330,9 +353,12 @@ public void initAndVerifyQueries() throws Exception { // 7 // Test multiple parentheses in limit syntax and in subquery qry = new Query( - "select id from (( (select * from UnitStatement_LimitEscape_t1 {limit 10})) ) t1 {limit ((1) )}", - "select TOP ((1) ) id from (( (select TOP 10 * from UnitStatement_LimitEscape_t1)) ) t1", 1, // # of - // rows + "select id from (( (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 10})) ) t1 {limit ((1) )}", + "select TOP ((1) ) id from (( (select TOP 10 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ")) ) t1", + 1, // # of + // rows 1, // # of columns new int[] {1}, // id column values null, // int column values @@ -342,8 +368,12 @@ public void initAndVerifyQueries() throws Exception { // 8 // Test limit syntax in multiple subqueries, also test arbitrary spaces in limit syntax qry = new Query( - "select j1.id from (( (select * from UnitStatement_LimitEscape_t1 {limit 10})) ) j1 join (select * from UnitStatement_LimitEscape_t2 {limit 4}) j2 on j1.id = j2.id {limit (1)}", - "select TOP (1) j1.id from (( (select TOP 10 * from UnitStatement_LimitEscape_t1)) ) j1 join (select TOP 4 * from UnitStatement_LimitEscape_t2) j2 on j1.id = j2.id", + "select j1.id from (( (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 10})) ) j1 join (select * from " + AbstractSQLGenerator.escapeIdentifier(table2) + + " {limit 4}) j2 on j1.id = j2.id {limit (1)}", + "select TOP (1) j1.id from (( (select TOP 10 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ")) ) j1 join (select TOP 4 * from " + AbstractSQLGenerator.escapeIdentifier(table2) + + ") j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -354,8 +384,12 @@ public void initAndVerifyQueries() throws Exception { // 9 // Test limit syntax in multiple levels of nested subqueries qry = new Query( - "select j1.id from (select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}) j1 join (select * from UnitStatement_LimitEscape_t2 {limit 4}) j2 on j1.id = j2.id {limit 1}", - "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3) j1 join (select TOP 4 * from UnitStatement_LimitEscape_t2) j2 on j1.id = j2.id", + "select j1.id from (select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}) j1 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table2) + " {limit 4}) j2 on j1.id = j2.id {limit 1}", + "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + ") j3) j1 join (select TOP 4 * from " + + AbstractSQLGenerator.escapeIdentifier(table2) + ") j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -366,8 +400,16 @@ public void initAndVerifyQueries() throws Exception { // 10 // Test limit syntax in multiple levels of nested subqueries as well as in outer query qry = new Query( - "select j1.id from (select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from UnitStatement_LimitEscape_t3 {limit 5}) j4 join (select * from UnitStatement_LimitEscape_t4 {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", - "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3) j1 join (select j4.id from (select TOP 5 * from UnitStatement_LimitEscape_t3) j4 join (select TOP 6 * from UnitStatement_LimitEscape_t4) j5 on j4.id = j5.id ) j2 on j1.id = j2.id", + "select j1.id from (select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + " {limit 5}) j4 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + " {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", + "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + ") j3) j1 join (select j4.id from (select TOP 5 * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + ") j4 join (select TOP 6 * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + ") j5 on j4.id = j5.id ) j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -377,8 +419,12 @@ public void initAndVerifyQueries() throws Exception { // 11 // Test multiple parentheses/spaces in limit syntax, also test '[]' in columns - qry = new Query("select [col1], col2, [col3], col4 from [UnitStatement_LimitEscape_t1] {limit ( ( (2)))}", - "select TOP ( ( (2))) [col1], col2, [col3], col4 from [UnitStatement_LimitEscape_t1]", 2, // # of rows + qry = new Query( + "select [col1], col2, [col3], col4 from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit ( ( (2)))}", + "select TOP ( ( (2))) [col1], col2, [col3], col4 from " + + AbstractSQLGenerator.escapeIdentifier(table1), + 2, // # of rows 4, // # of columns new int[] {1, 2}, // id column values new int[][] {{1, 1}, {2, 2}}, // int column values @@ -390,8 +436,16 @@ public void initAndVerifyQueries() throws Exception { // 12 // Test complicated query with nested subquery having limit syntax qry = new Query( - "select j1.id from ( ((select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}))) j1 join (select j4.id from ((((select * from UnitStatement_LimitEscape_t3 {limit 5})))) j4 join (select * from UnitStatement_LimitEscape_t4 {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", - "select TOP 1 j1.id from ( ((select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3))) j1 join (select j4.id from ((((select TOP 5 * from UnitStatement_LimitEscape_t3)))) j4 join (select TOP 6 * from UnitStatement_LimitEscape_t4) j5 on j4.id = j5.id ) j2 on j1.id = j2.id", + "select j1.id from ( ((select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}))) j1 join (select j4.id from ((((select * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + " {limit 5})))) j4 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + " {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", + "select TOP 1 j1.id from ( ((select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + ") j3))) j1 join (select j4.id from ((((select TOP 5 * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + ")))) j4 join (select TOP 6 * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + ") j5 on j4.id = j5.id ) j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -401,8 +455,9 @@ public void initAndVerifyQueries() throws Exception { // 13 // Test prepared statements with limit syntax with multiple parentheses/spaces - qry = new PreparedQuery("select * from UnitStatement_LimitEscape_t1 {limit ( ( (?)))}", - "select TOP ( ( (?))) * from UnitStatement_LimitEscape_t1", 1, // # of rows + qry = new PreparedQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit ( ( (?)))}", + "select TOP ( ( (?))) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -411,10 +466,10 @@ public void initAndVerifyQueries() throws Exception { // 14 // Test prepared statements with limit syntax - qry = new PreparedQuery("select * from UnitStatement_LimitEscape_t1 {limit (?)}", - "select TOP (?) * from UnitStatement_LimitEscape_t1", 1, // # - // of - // rows + qry = new PreparedQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit (?)}", + "select TOP (?) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # + // of + // rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -423,10 +478,10 @@ public void initAndVerifyQueries() throws Exception { // 15 // Test prepared statements with limit syntax with multiple parentheses/spaces - qry = new PreparedQuery("select * from UnitStatement_LimitEscape_t1 {limit ?}", - "select TOP (?) * from UnitStatement_LimitEscape_t1", 1, // # - // of - // rows + qry = new PreparedQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit ?}", + "select TOP (?) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # + // of + // rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -435,8 +490,12 @@ public void initAndVerifyQueries() throws Exception { // 16 // Test prepared statements with limit syntax with subqueries - qry = new PreparedQuery("select * from (select * from UnitStatement_LimitEscape_t1 {limit ?}) t1 {limit (?)}", - "select TOP (?) * from (select TOP (?) * from UnitStatement_LimitEscape_t1) t1", 1, // # of rows + qry = new PreparedQuery( + "select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit ?}) t1 {limit (?)}", + "select TOP (?) * from (select TOP (?) * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ") t1", + 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -445,8 +504,10 @@ public void initAndVerifyQueries() throws Exception { // 17 // Test callable statements as they are also translated by the driver - qry = new CallableQuery("EXEC UnitStatement_LimitEscape_p1 @col3Value = 'col3', @col4Value = 'col4'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'col3', @col4Value = 'col4'", 1, // # of rows + qry = new CallableQuery( + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col3Value = 'col3', @col4Value = 'col4'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col3Value = 'col3', @col4Value = 'col4'", + 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -456,8 +517,10 @@ public void initAndVerifyQueries() throws Exception { // 18 // Test callable statements with limit syntax in string literals qry = new CallableQuery( - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", 1, // # // of // rows @@ -469,9 +532,10 @@ public void initAndVerifyQueries() throws Exception { // 19 // Test callable statements with subquery/limit syntax in string literals - qry = new CallableQuery( - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", + qry = new CallableQuery("EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", 1, // # of rows 5, // # of columns new int[] {3}, // id column values @@ -483,9 +547,10 @@ public void initAndVerifyQueries() throws Exception { // 20 // Test callable statements with quotes/scalar functions/limit syntax in string literals - qry = new CallableQuery( - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", + qry = new CallableQuery("EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", 1, // # of rows 5, // # of columns new int[] {4}, // id column values @@ -496,9 +561,13 @@ public void initAndVerifyQueries() throws Exception { // 21 // Test callable statement escape syntax with quotes/scalar functions/limit syntax in string literals qry = new CallableQuery( - "{call UnitStatement_LimitEscape_p1 ('select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)')}", - "EXEC UnitStatement_LimitEscape_p1 'select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)'", - 1, // # of rows + "{call " + AbstractSQLGenerator.escapeIdentifier(procName) + + " ('select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)')}", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " 'select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)'", + 1, // # + // of + // rows 5, // # of columns new int[] {4}, // id column values new int[][] {{4, 4}}, // int column value @@ -507,9 +576,10 @@ public void initAndVerifyQueries() throws Exception { // 22 // Test callable statement escape syntax with openrowquery/openrowset/quotes in string literals - qry = new CallableQuery( - "{call UnitStatement_LimitEscape_p1 ('openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')')}", - "EXEC UnitStatement_LimitEscape_p1 'openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')'", + qry = new CallableQuery("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + + " ('openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')')}", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " 'openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')'", 1, // # // of // rows @@ -524,10 +594,13 @@ public void initAndVerifyQueries() throws Exception { // 23 // Test openquery syntax translation with limit syntax qry = new Query( - "select * from openquery('linked_server', 'select * from UnitStatement_LimitEscape_t1 {limit 2}') {limit 1}", - "select TOP 1 * from openquery('linked_server', 'select TOP 2 * from UnitStatement_LimitEscape_t1')", 1, // # - // of - // rows + "select * from openquery('linked_server', 'select * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 2}') {limit 1}", + "select TOP 1 * from openquery('linked_server', 'select TOP 2 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + "')", + 1, // # + // of + // rows 5, // # of columns new int[] {5}, // id column values new int[][] {{5, 5}}, // int column value @@ -537,8 +610,18 @@ public void initAndVerifyQueries() throws Exception { // 24 // Test openrowset syntax translation with a complicated query with subqueries and limit syntax qry = new Query( - "select * from openrowset('provider_name', 'provider_string', 'select j1.id from (select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from UnitStatement_LimitEscape_t3 {limit 5}) j4 join (select * from UnitStatement_LimitEscape_t4 {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}') {limit 1}", - "select TOP 1 * from openrowset('provider_name', 'provider_string', 'select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3) j1 join (select j4.id from (select TOP 5 * from UnitStatement_LimitEscape_t3) j4 join (select TOP 6 * from UnitStatement_LimitEscape_t4) j5 on j4.id = j5.id ) j2 on j1.id = j2.id')", + "select * from openrowset('provider_name', 'provider_string', 'select j1.id from (select * from (select * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + " {limit 5}) j4 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + " {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}') {limit 1}", + "select TOP 1 * from openrowset('provider_name', 'provider_string', 'select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + ") j3) j1 join (select j4.id from (select TOP 5 * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + ") j4 join (select TOP 6 * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + ") j5 on j4.id = j5.id ) j2 on j1.id = j2.id')", 1, // # of rows 5, // # of columns new int[] {5}, // id column values @@ -547,8 +630,10 @@ public void initAndVerifyQueries() throws Exception { // 25 // Test offset syntax in string literals - qry = new Query("select * from UnitStatement_LimitEscape_t1 where col3 = '{limit 1 offset 2}'", - "select * from UnitStatement_LimitEscape_t1 where col3 = '{limit 1 offset 2}'", 0, // # of rows + qry = new Query( + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = '{limit 1 offset 2}'", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = '{limit 1 offset 2}'", + 0, // # of rows 5, // # of columns null, // id column values null, // int column values @@ -560,10 +645,13 @@ public void initAndVerifyQueries() throws Exception { // Only test the syntax translation. // Test batch query. qry = new Query( - "select * from UnitStatement_LimitEscape_t1 {limit 1}; select * from UnitStatement_LimitEscape_t1 {limit 4}", - "select TOP 1 * from UnitStatement_LimitEscape_t1; select TOP 4 * from UnitStatement_LimitEscape_t1", 0, // # - // of - // rows + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}; select * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 4}", + "select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + "; select TOP 4 * from " + + AbstractSQLGenerator.escapeIdentifier(table1), + 0, // # + // of + // rows 5, // # of columns null, // id column values null, // int column values @@ -571,8 +659,9 @@ public void initAndVerifyQueries() throws Exception { // 27 // Execute query, and verify exception for unclosed quotation marks. - qry = new Query("select * from UnitStatement_LimitEscape_t1 where col3 = 'abcd", - "select * from UnitStatement_LimitEscape_t1 where col3 = 'abcd", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = 'abcd", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = 'abcd", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -583,20 +672,20 @@ public void initAndVerifyQueries() throws Exception { // 28 // Execute query, and verify exception for unclosed subquery. - qry = new Query("select * from (select * from UnitStatement_LimitEscape_t1 {limit 1}", - "select * from (select TOP 1 * from UnitStatement_LimitEscape_t1", 0, // # of rows + qry = new Query("select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}", + "select * from (select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1), 0, // # of rows 0, // # of columns null, // id column values null, // int column values null); // string column values // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near 'UnitStatement_LimitEscape_t1'."); + qry.setExceptionMsg("Incorrect syntax near '" + table1 + "'."); qry.execute(conn); // 29 // Execute query, and verify exception for syntax error in select. - qry = new Query("selectsel * from from UnitStatement_LimitEscape_t1 {limit 1}", - "selectsel * from from UnitStatement_LimitEscape_t1 {limit 1}", 0, // # of rows + qry = new Query("selectsel * from from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}", + "selectsel * from from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -608,8 +697,8 @@ public void initAndVerifyQueries() throws Exception { // 29 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit1}", - "select * from UnitStatement_LimitEscape_t1 {limit1}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -621,9 +710,9 @@ public void initAndVerifyQueries() throws Exception { // 30 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit(1}", - "select * from UnitStatement_LimitEscape_t1 {limit(1}", 0, // # of - // rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit(1}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit(1}", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -635,8 +724,9 @@ public void initAndVerifyQueries() throws Exception { // 31 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit 1 offset10}", - "select * from UnitStatement_LimitEscape_t1 {limit 1 offset10}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1 offset10}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1 offset10}", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -648,8 +738,9 @@ public void initAndVerifyQueries() throws Exception { // 32 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit1 offset 10}", - "select * from UnitStatement_LimitEscape_t1 {limit1 offset 10}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset 10}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset 10}", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -661,8 +752,8 @@ public void initAndVerifyQueries() throws Exception { // 33 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit1 offset10}", - "select * from UnitStatement_LimitEscape_t1 {limit1 offset10}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset10}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset10}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -674,8 +765,9 @@ public void initAndVerifyQueries() throws Exception { // 34 // Execute query, and verify exception for syntax error. The translator should leave the query unchanged as // limit syntax is not correct. - qry = new Query("insert into UnitStatement_LimitEscape_t1(col3) values({limit 1})", - "insert into UnitStatement_LimitEscape_t1(col3) values({limit 1})", 0, // # of rows + qry = new Query("insert into " + AbstractSQLGenerator.escapeIdentifier(table1) + "(col3) values({limit 1})", + "insert into " + AbstractSQLGenerator.escapeIdentifier(table1) + "(col3) values({limit 1})", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -687,10 +779,10 @@ public void initAndVerifyQueries() throws Exception { // 35 // Execute query, and verify exception for syntax error. The translator should leave the query unchanged as // limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit {limit 5}}", - "select TOP 5 * from UnitStatement_LimitEscape_t1 {limit}", 0, // # - // of - // rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit {limit 5}}", + "select TOP 5 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit}", 0, // # + // of + // rows 0, // # of columns null, // id column values null, // int column values @@ -702,8 +794,8 @@ public void initAndVerifyQueries() throws Exception { // 36 // Execute query, and verify exception for syntax error. The translator should leave the query unchanged as // limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit 1} {limit 2}", - "select TOP 1 * from UnitStatement_LimitEscape_t1 {limit 2}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1} {limit 2}", + "select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 2}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -723,12 +815,22 @@ public void initAndVerifyQueries() throws Exception { @Test @DisplayName("verifyOffsetException") public void verifyOffsetException() throws Exception { - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit 2 offset 1}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit 2232 offset 1232}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit (2) offset (1)}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit (265) offset (1972)}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit ? offset ?}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit (?) offset (?)}"); + offsetQuery.addElement("select * from " + + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + " {limit 2 offset 1}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit 2232 offset 1232}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit (2) offset (1)}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit (265) offset (1972)}"); + offsetQuery.addElement("select * from " + + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + " {limit ? offset ?}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit (?) offset (?)}"); int i; for (i = 0; i < offsetQuery.size(); ++i) { @@ -749,7 +851,8 @@ public void verifyOffsetException() throws Exception { // Test the parsing error with unmatched braces in limit clause try { // Do not execute query. Exception will be thrown when verifying translation. - Query qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit (2))}", "", 0, // # of rows + Query qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit (2))}", + "", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -783,10 +886,11 @@ public static void beforeAll() { public static void afterAll() throws Exception { try (Statement stmt = conn.createStatement()) { - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t4", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table3), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table4), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), 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 5e5c0ffb1..2d00d9cdc 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 @@ -18,8 +18,10 @@ 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.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; @@ -30,17 +32,28 @@ */ @RunWith(JUnitPlatform.class) public class MergeTest extends AbstractTest { - private static final String setupTables = "IF OBJECT_ID (N'dbo.CricketTeams', N'U') IS NOT NULL DROP TABLE dbo.CricketTeams;" - + " CREATE TABLE dbo.CricketTeams ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" - + " INSERT INTO dbo.CricketTeams VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia'), (6, 'HongKong', 'Asia')," + static String cricketTeams = RandomUtil.getIdentifier("CricketTeams"); + static String cricketTeamsUpdated = RandomUtil.getIdentifier("cricketTeamsUpdated"); + + private static final String setupTables = "IF OBJECT_ID (N'" + TestUtils.escapeSingleQuotes(cricketTeams) + + "', N'U') IS NOT NULL DROP TABLE " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + ";" + + " CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + + " ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + + " VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia'), (6, 'HongKong', 'Asia')," + " (7, 'U.A.E', 'Asia'), (8, 'England', 'Europe'), (9, 'South Africa', 'Africa'), (10, 'West Indies', 'North America');" - + " SELECT * FROM CricketTeams IF OBJECT_ID (N'dbo.CricketTeams_UpdatedList', N'U') IS NOT NULL DROP TABLE dbo.CricketTeams_UpdatedList;" - + " CREATE TABLE dbo.CricketTeams_UpdatedList ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" - + "INSERT INTO dbo.CricketTeams_UpdatedList VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia')," + + " SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + " IF OBJECT_ID (N'" + + TestUtils.escapeSingleQuotes(cricketTeams) + "_UpdatedList', N'U') IS NOT NULL DROP TABLE " + + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + ";" + " CREATE TABLE " + + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + + " ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" + + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + + " VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia')," + " (6, 'Thailand', 'Asia'), (8, 'England', 'Europe'), (9, 'South Africa', 'Africa'), (10, 'West Indies', 'North America'), (11, 'Zimbabwe', 'Africa');"; - private static final String mergeCmd2 = "MERGE dbo.CricketTeams AS TARGET " - + "USING dbo.CricketTeams_UpdatedList AS SOURCE " + "ON (TARGET.CricketTeamID = SOURCE.CricketTeamID) " + private static final String mergeCmd2 = "MERGE " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + + " AS TARGET " + "USING " + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + " AS SOURCE " + + "ON (TARGET.CricketTeamID = SOURCE.CricketTeamID) " + "WHEN MATCHED AND TARGET.CricketTeamContinent <> SOURCE.CricketTeamContinent OR " + "TARGET.CricketTeamCountry <> SOURCE.CricketTeamCountry " + "THEN UPDATE SET TARGET.CricketTeamContinent = SOURCE.CricketTeamContinent ," @@ -81,7 +94,8 @@ public static void afterAll() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists("dbo.CricketTeams", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(cricketTeams), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated), 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 b50b36278..c5a654cf2 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 @@ -19,8 +19,10 @@ 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; @@ -30,8 +32,8 @@ */ @RunWith(JUnitPlatform.class) public class NamedParamMultiPartTest extends AbstractTest { - private static final String dataPut = "eminem"; - String procedureName = "mystoredproc"; + private static final String dataPut = RandomUtil.getIdentifier("dataPut"); + static String procedureName; /** * setup @@ -40,11 +42,13 @@ public class NamedParamMultiPartTest extends AbstractTest { */ @BeforeAll public static void beforeAll() throws SQLException { + procedureName = RandomUtil.getIdentifier("mystoredproc"); + try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement()) { - TestUtils.dropProcedureIfExists("mystoredproc", statement); - statement.executeUpdate( - "CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), statement); + statement.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + + " (@p_out varchar(255) OUTPUT) AS set @p_out = '" + TestUtils.escapeSingleQuotes(dataPut) + "'"); } } @@ -55,8 +59,8 @@ public static void beforeAll() throws SQLException { */ @Test public void update1() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); String data = cs.getString("p_out"); @@ -71,8 +75,8 @@ public void update1() throws Exception { */ @Test public void update2() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -88,7 +92,7 @@ public void update2() throws Exception { @Test public void update3() throws Exception { String catalog = connection.getCatalog(); - String storedproc = "[" + catalog + "]" + ".[dbo].[mystoredproc]"; + String storedproc = "[" + catalog + "]" + ".[dbo]." + AbstractSQLGenerator.escapeIdentifier(procedureName); try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); @@ -105,8 +109,8 @@ public void update3() throws Exception { */ @Test public void update4() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -121,8 +125,8 @@ public void update4() throws Exception { */ @Test public void update5() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -137,7 +141,7 @@ public void update5() throws Exception { @Test public void update6() throws Exception { String catalog = connection.getCatalog(); - String storedproc = catalog + ".dbo." + procedureName; + String storedproc = catalog + ".dbo." + AbstractSQLGenerator.escapeIdentifier(procedureName); try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); @@ -156,7 +160,7 @@ public void update6() throws Exception { public static void afterAll() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - TestUtils.dropProcedureIfExists("mystoredproc", stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), 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 32352d8cf..86e150397 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 @@ -46,22 +46,16 @@ public class PQImpsTest extends AbstractTest { private static ResultSet versionRS = null; private static int version = -1; - private static String nameTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("names_DB")); - private static String phoneNumberTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("phoneNumbers_DB")); - private static String mergeNameDesTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("mergeNameDesTable_DB")); - private static String numericTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("numericTable_DB")); - private static String charTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("charTable_DB")); - private static String charTable2 = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("charTable2_DB")); - private static String binaryTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("binaryTable_DB")); - private static String dateAndTimeTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("dateAndTimeTable_DB")); - private static String multipleTypesTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("multipleTypesTable_DB")); - private static String spaceTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("spaceTable_DB")); + private static String nameTable = RandomUtil.getIdentifier("names_DB"); + private static String phoneNumberTable = RandomUtil.getIdentifier("phoneNumbers_DB"); + private static String mergeNameDesTable = RandomUtil.getIdentifier("mergeNameDesTable_DB"); + private static String numericTable = RandomUtil.getIdentifier("numericTable_DB"); + private static String charTable = RandomUtil.getIdentifier("charTable_DB"); + private static String charTable2 = RandomUtil.getIdentifier("charTable2_DB"); + private static String binaryTable = RandomUtil.getIdentifier("binaryTable_DB"); + private static String dateAndTimeTable = RandomUtil.getIdentifier("dateAndTimeTable_DB"); + private static String multipleTypesTable = RandomUtil.getIdentifier("multipleTypesTable_DB"); + private static String spaceTable = RandomUtil.getIdentifier("spaceTable_DB"); /** * Setup @@ -330,9 +324,9 @@ private static void compareParameterMetaData(ParameterMetaData pmd, int index, S } private static void populateNumericTable() throws SQLException { - stmt.execute("insert into " + numericTable + " values (" + "1.123," + "1.123," + "1.2345," + "1.2345," - + "1.543," + "1.543," + "5.1234," + "104935," + "34323," + "123," + "5," + "1.45," + "1.3," - + "0.123456789," + "0.1234567890123456789012345678901234567" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values (" + "1.123," + + "1.123," + "1.2345," + "1.2345," + "1.543," + "1.543," + "5.1234," + "104935," + "34323," + "123," + + "5," + "1.45," + "1.3," + "0.123456789," + "0.1234567890123456789012345678901234567" + ")"); } private static void testBeforeExcute() throws SQLException { @@ -340,9 +334,10 @@ private static void testBeforeExcute() throws SQLException { pstmt.close(); } - String sql = "select * from " + numericTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? and " - + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + "c14 = ? and " + "c15 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + + "c8 = ? and " + "c9 = ? and " + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + + "c14 = ? and " + "c15 = ? "; pstmt = connection.prepareStatement(sql); @@ -354,9 +349,10 @@ private static void testBeforeExcute() throws SQLException { } private static void selectNumeric() throws SQLException { - String sql = "select * from " + numericTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? and " - + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + "c14 = ? and " + "c15 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + + "c8 = ? and " + "c9 = ? and " + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + + "c14 = ? and " + "c15 = ? "; pstmt = connection.prepareStatement(sql); @@ -369,8 +365,8 @@ private static void selectNumeric() throws SQLException { private static void insertNumeric() throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," - + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?," + "?," + + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ")"; pstmt = connection.prepareStatement(sql); @@ -383,9 +379,9 @@ private static void insertNumeric() throws SQLException { private static void updateNumeric() throws SQLException { - String sql = "update " + numericTable + " set " + "c1 = ?," + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," - + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?," + "c10 = ?," + "c11 = ?," + "c12 = ?," + "c13 = ?," - + "c14 = ?," + "c15 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " set " + "c1 = ?," + "c2 = ?," + + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?," + "c10 = ?," + + "c11 = ?," + "c12 = ?," + "c13 = ?," + "c14 = ?," + "c15 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -398,9 +394,10 @@ private static void updateNumeric() throws SQLException { private static void deleteNumeric() throws SQLException { - String sql = "delete from " + numericTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? and " - + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + "c14 = ? and " + "c15 = ?" + ";"; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + + "c8 = ? and " + "c9 = ? and " + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + + "c14 = ? and " + "c15 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -413,38 +410,41 @@ private static void deleteNumeric() throws SQLException { private static void createNumericTable() throws SQLException { - stmt.execute("Create table " + numericTable + " (" + "c1 decimal not null," + "c2 decimal(10,5) not null," - + "c3 numeric not null," + "c4 numeric(8,4) not null," + "c5 float not null," + "c6 float(10) not null," - + "c7 real not null," + "c8 int not null," + "c9 bigint not null," + "c10 smallint not null," - + "c11 tinyint not null," + "c12 money not null," + "c13 smallmoney not null," - + "c14 decimal(10,9) not null," + "c15 decimal(38,37) not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + + "c1 decimal not null," + "c2 decimal(10,5) not null," + "c3 numeric not null," + + "c4 numeric(8,4) not null," + "c5 float not null," + "c6 float(10) not null," + "c7 real not null," + + "c8 int not null," + "c9 bigint not null," + "c10 smallint not null," + "c11 tinyint not null," + + "c12 money not null," + "c13 smallmoney not null," + "c14 decimal(10,9) not null," + + "c15 decimal(38,37) not null" + ")"); } private static void createCharTable() throws SQLException { - stmt.execute("Create table " + charTable + " (" + "c1 char(50) not null," + "c2 varchar(20) not null," - + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," + "c5 text not null," + "c6 ntext not null" - + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (" + "c1 char(50) not null," + + "c2 varchar(20) not null," + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," + + "c5 text not null," + "c6 ntext not null" + ")"); } private static void createSpaceTable() throws SQLException { - stmt.execute("Create table " + spaceTable + " (" + "[c1*/someString withspace] char(50) not null," - + "c2 varchar(20) not null," + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," - + "c5 text not null," + "c6 ntext not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(spaceTable) + " (" + + "[c1*/someString withspace] char(50) not null," + "c2 varchar(20) not null," + + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," + "c5 text not null," + "c6 ntext not null" + + ")"); } private static void createChar2Table() throws SQLException { - stmt.execute("Create table " + charTable2 + " (" + "table2c1 char(50) not null)"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(charTable2) + " (" + + "table2c1 char(50) not null)"); } private static void populateCharTable() throws SQLException { - stmt.execute("insert into " + charTable + " values (" + "'Hello'," + "'Hello'," + "N'Hello'," + "N'Hello'," - + "'Hello'," + "N'Hello'" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values (" + "'Hello'," + + "'Hello'," + "N'Hello'," + "N'Hello'," + "'Hello'," + "N'Hello'" + ")"); } private static void selectChar() throws SQLException { - String sql = "select * from " + charTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? "; pstmt = connection.prepareStatement(sql); @@ -457,7 +457,8 @@ private static void selectChar() throws SQLException { private static void insertChar() throws SQLException { - String sql = "insert into " + charTable + " values( " + "?," + "?," + "?," + "?," + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?," + "?," + + "?," + "?," + "?," + "?" + ")"; pstmt = connection.prepareStatement(sql); @@ -470,8 +471,8 @@ private static void insertChar() throws SQLException { private static void updateChar() throws SQLException { - String sql = "update " + charTable + " set " + "c1 = ?," + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," - + "c6 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(charTable) + " set " + "c1 = ?," + "c2 = ?," + + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -484,7 +485,8 @@ private static void updateChar() throws SQLException { private static void deleteChar() throws SQLException { - String sql = "delete from " + charTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " + "c4 = ? "; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? "; pstmt = connection.prepareStatement(sql); @@ -497,18 +499,19 @@ private static void deleteChar() throws SQLException { private static void createBinaryTable() throws SQLException { - stmt.execute( - "Create table " + binaryTable + " (" + "c1 binary(100) not null," + "c2 varbinary(200) not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " (" + + "c1 binary(100) not null," + "c2 varbinary(200) not null" + ")"); } private static void populateBinaryTable() throws SQLException { - stmt.execute("insert into " + binaryTable + " values (" + "convert(binary(50), 'Simba tech', 0), " - + "convert(varbinary(50), 'Simba tech', 0)" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values (" + + "convert(binary(50), 'Simba tech', 0), " + "convert(varbinary(50), 'Simba tech', 0)" + ")"); } private static void selectBinary() throws SQLException { - String sql = "select * from " + binaryTable + " where " + "c1 = ? and " + "c2 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " where " + "c1 = ? and " + + "c2 = ? "; pstmt = connection.prepareStatement(sql); @@ -521,7 +524,8 @@ private static void selectBinary() throws SQLException { private static void insertBinary() throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?," + "?" + + ")"; pstmt = connection.prepareStatement(sql); @@ -535,7 +539,8 @@ private static void insertBinary() throws SQLException { private static void updateBinary() throws SQLException { - String sql = "update " + binaryTable + " set " + "c1 = ?," + "c2 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " set " + "c1 = ?," + "c2 = ?" + + ";"; pstmt = connection.prepareStatement(sql); @@ -549,7 +554,8 @@ private static void updateBinary() throws SQLException { private static void deleteBinary() throws SQLException { - String sql = "delete from " + binaryTable + " where " + "c1 = ? and " + "c2 = ?" + ";"; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " where " + "c1 = ? and " + + "c2 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -562,22 +568,23 @@ private static void deleteBinary() throws SQLException { private static void createDateAndTimeTable() throws SQLException { - stmt.execute("Create table " + dateAndTimeTable + " (" + "c1 date not null," + "c2 datetime not null," - + "c3 datetime2 not null," + "c4 datetime2(5) not null," + "c5 datetimeoffset not null," - + "c6 datetimeoffset(5) not null," + "c7 smalldatetime not null," + "c8 time not null," - + "c9 time(5) not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " (" + + "c1 date not null," + "c2 datetime not null," + "c3 datetime2 not null," + "c4 datetime2(5) not null," + + "c5 datetimeoffset not null," + "c6 datetimeoffset(5) not null," + "c7 smalldatetime not null," + + "c8 time not null," + "c9 time(5) not null" + ")"); } private static void populateDateAndTimeTable() throws SQLException { - stmt.execute("insert into " + dateAndTimeTable + " values (" + "'1991-10-23'," + "'1991-10-23 06:20:50'," - + "'1991-10-23 07:20:50.123'," + "'1991-10-23 07:20:50.123'," + "'1991-10-23 08:20:50.123'," - + "'1991-10-23 08:20:50.123'," + "'1991-10-23 09:20:50'," + "'10:20:50'," + "'10:20:50'" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " values (" + + "'1991-10-23'," + "'1991-10-23 06:20:50'," + "'1991-10-23 07:20:50.123'," + + "'1991-10-23 07:20:50.123'," + "'1991-10-23 08:20:50.123'," + "'1991-10-23 08:20:50.123'," + + "'1991-10-23 09:20:50'," + "'10:20:50'," + "'10:20:50'" + ")"); } private static void insertDateAndTime() throws SQLException { - String sql = "insert into " + dateAndTimeTable + " values( " + "?," + "?," + "?," + "?," + "?," + "?," + "?," - + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " values( " + "?," + + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ")"; pstmt = connection.prepareStatement(sql); @@ -590,8 +597,8 @@ private static void insertDateAndTime() throws SQLException { private static void updateDateAndTime() throws SQLException { - String sql = "update " + dateAndTimeTable + " set " + "c1 = ?," + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," - + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " set " + "c1 = ?," + + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -604,8 +611,9 @@ private static void updateDateAndTime() throws SQLException { private static void deleteDateAndTime() throws SQLException { - String sql = "delete from " + dateAndTimeTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ?" + ";"; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " where " + + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + + "c7 = ? and " + "c8 = ? and " + "c9 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -617,8 +625,9 @@ private static void deleteDateAndTime() throws SQLException { } private static void selectDateAndTime() throws SQLException { - String sql = "select * from " + dateAndTimeTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " where " + + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + + "c7 = ? and " + "c8 = ? and " + "c9 = ? "; pstmt = connection.prepareStatement(sql); @@ -631,15 +640,15 @@ private static void selectDateAndTime() throws SQLException { private static void createTablesForCompexQueries() throws SQLException { stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(nameTable) + "','U') is not null" - + " drop table " + nameTable); + + " drop table " + AbstractSQLGenerator.escapeIdentifier(nameTable)); stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(phoneNumberTable) + "','U') is not null" - + " drop table " + phoneNumberTable); + + " drop table " + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable)); stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(mergeNameDesTable) + "','U') is not null" - + " drop table " + mergeNameDesTable); + + " drop table " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable)); - String sql = "create table " + nameTable + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " (" // + "ID int NOT NULL," + "PlainID int not null," + "ID smallint NOT NULL," + "FirstName varchar(50) NOT NULL," + "LastName nchar(60) NOT NULL" + ");"; @@ -650,8 +659,8 @@ private static void createTablesForCompexQueries() throws SQLException { fail(e.toString()); } - sql = "create table " + phoneNumberTable + " (" + "PlainID smallint not null," + "ID int NOT NULL," - + "PhoneNumber bigint NOT NULL" + ");"; + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + " (" + + "PlainID smallint not null," + "ID int NOT NULL," + "PhoneNumber bigint NOT NULL" + ");"; try { stmt.execute(sql); @@ -659,7 +668,7 @@ private static void createTablesForCompexQueries() throws SQLException { fail(e.toString()); } - sql = "create table " + mergeNameDesTable + " (" + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable) + " (" // + "ID int NOT NULL," + "PlainID smallint not null," + "ID int NULL," + "FirstName char(30) NULL," + "LastName varchar(50) NULL" + ");"; @@ -672,7 +681,8 @@ private static void createTablesForCompexQueries() throws SQLException { } private static void populateTablesForCompexQueries() throws SQLException { - String sql = "insert into " + nameTable + " values " + "(?,?,?,?)," + "(?,?,?,?)," + "(?,?,?,?)" + ""; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " values " + "(?,?,?,?)," + + "(?,?,?,?)," + "(?,?,?,?)" + ""; pstmt = connection.prepareStatement(sql); int id = 1; for (int i = 0; i < 5; i++) { @@ -697,7 +707,8 @@ private static void populateTablesForCompexQueries() throws SQLException { } pstmt.close(); - sql = "insert into " + phoneNumberTable + " values " + "(?,?,?)," + "(?,?,?)," + "(?,?,?)" + ""; + sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + " values " + "(?,?,?)," + + "(?,?,?)," + "(?,?,?)" + ""; pstmt = connection.prepareStatement(sql); id = 1; for (int i = 0; i < 5; i++) { @@ -719,7 +730,8 @@ private static void populateTablesForCompexQueries() throws SQLException { } pstmt.close(); - sql = "insert into " + mergeNameDesTable + " (PlainID) values " + "(?)," + "(?)," + "(?)" + ""; + sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable) + " (PlainID) values " + "(?)," + + "(?)," + "(?)" + ""; pstmt = connection.prepareStatement(sql); id = 1; for (int i = 0; i < 5; i++) { @@ -745,8 +757,10 @@ private static void populateTablesForCompexQueries() throws SQLException { @DisplayName("SubQuery") public void testSubquery() throws SQLException { if (version >= SQL_SERVER_2012_VERSION) { - String sql = "SELECT FirstName,LastName" + " FROM " + nameTable + " WHERE ID IN " + " (SELECT ID" + " FROM " - + phoneNumberTable + " WHERE PhoneNumber = ? and ID = ? and PlainID = ?" + ")"; + String sql = "SELECT FirstName,LastName" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + + " WHERE ID IN " + " (SELECT ID" + " FROM " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + + " WHERE PhoneNumber = ? and ID = ? and PlainID = ?" + ")"; pstmt = connection.prepareStatement(sql); @@ -777,8 +791,14 @@ public void testJoin() throws SQLException { String sql = String.format( "select %s.FirstName, %s.LastName, %s.PhoneNumber" + " from %s join %s on %s.PlainID = %s.PlainID" + " where %s.ID = ? and %s.PlainID = ?", - nameTable, nameTable, phoneNumberTable, nameTable, phoneNumberTable, nameTable, phoneNumberTable, - phoneNumberTable, phoneNumberTable); + AbstractSQLGenerator.escapeIdentifier(nameTable), AbstractSQLGenerator.escapeIdentifier(nameTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(nameTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(nameTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable)); pstmt = connection.prepareStatement(sql); @@ -805,8 +825,9 @@ public void testJoin() throws SQLException { @DisplayName("Merge Queries") public void testMerge() throws SQLException { if (version >= SQL_SERVER_2012_VERSION) { - String sql = "merge " + mergeNameDesTable + " as T" + " using " + nameTable + " as S" - + " on T.PlainID=S.PlainID" + " when matched" + " then update set T.firstName = ?, T.lastName = ?;"; + String sql = "merge " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable) + " as T" + " using " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + " as S" + " on T.PlainID=S.PlainID" + + " when matched" + " then update set T.firstName = ?, T.lastName = ?;"; pstmt = connection.prepareStatement(sql); @@ -830,11 +851,11 @@ public void testMerge() throws SQLException { private static void createMultipleTypesTable() throws SQLException { - stmt.execute("Create table " + multipleTypesTable + " (" + "c1n decimal not null," - + "c2n decimal(10,5) not null," + "c3n numeric not null," + "c4n numeric(8,4) not null," - + "c5n float not null," + "c6n float(10) not null," + "c7n real not null," + "c8n int not null," - + "c9n bigint not null," + "c10n smallint not null," + "c11n tinyint not null," + "c12n money not null," - + "c13n smallmoney not null," + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable) + " (" + + "c1n decimal not null," + "c2n decimal(10,5) not null," + "c3n numeric not null," + + "c4n numeric(8,4) not null," + "c5n float not null," + "c6n float(10) not null," + + "c7n real not null," + "c8n int not null," + "c9n bigint not null," + "c10n smallint not null," + + "c11n tinyint not null," + "c12n money not null," + "c13n smallmoney not null," + "c1c char(50) not null," + "c2c varchar(20) not null," + "c3c nchar(30) not null," + "c4c nvarchar(60) not null," + "c5c text not null," + "c6c ntext not null," @@ -848,8 +869,8 @@ private static void createMultipleTypesTable() throws SQLException { private static void testInsertMultipleTypes() throws SQLException { - String sql = "insert into " + multipleTypesTable + " values( " + "?,?,?,?,?,?,?,?,?,?,?,?,?," + "?,?,?,?,?,?," - + "?,?," + "?,?,?,?,?,?,?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable) + " values( " + + "?,?,?,?,?,?,?,?,?,?,?,?,?," + "?,?,?,?,?,?," + "?,?," + "?,?,?,?,?,?,?,?,?" + ")"; pstmt = connection.prepareStatement(sql); @@ -919,7 +940,7 @@ private static void testInsertMultipleTypes() throws SQLException { @Test @DisplayName("testNoParameter") public void testNoParameter() throws SQLException { - String sql = "select * from " + multipleTypesTable; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable); pstmt = connection.prepareStatement(sql); @@ -936,8 +957,9 @@ public void testNoParameter() throws SQLException { private static void testMixedWithHardcodedValues() throws SQLException { - String sql = "insert into " + multipleTypesTable + " values( " + "1,?,?,1,?,?,?,1,?,?,?,1,1," - + "?,'simba tech','simba tech',?,?,?," + "?,?," + "?,'1991-10-23',?,?,?,'1991-10-23',?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable) + " values( " + + "1,?,?,1,?,?,?,1,?,?,?,1,1," + "?,'simba tech','simba tech',?,?,?," + "?,?," + + "?,'1991-10-23',?,?,?,'1991-10-23',?,?,?" + ")"; pstmt = connection.prepareStatement(sql); @@ -1000,7 +1022,7 @@ private static void testMixedWithHardcodedValues() throws SQLException { @Test @DisplayName("Test OrderBy") public void testOrderBy() throws SQLException { - String sql = "SELECT FirstName,LastName" + " FROM " + nameTable + String sql = "SELECT FirstName,LastName" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? " + " ORDER BY ID ASC"; pstmt = connection.prepareStatement(sql); @@ -1029,7 +1051,7 @@ public void testOrderBy() throws SQLException { @Test @DisplayName("Test GroupBy") private void testGroupBy() throws SQLException { - String sql = "SELECT FirstName,COUNT(LastName)" + " FROM " + nameTable + String sql = "SELECT FirstName,COUNT(LastName)" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? " + " group by Firstname"; pstmt = connection.prepareStatement(sql); @@ -1057,7 +1079,7 @@ private void testGroupBy() throws SQLException { */ @Test public void testLower() throws SQLException { - String sql = "SELECT FirstName,LOWER(LastName)" + " FROM " + nameTable + String sql = "SELECT FirstName,LOWER(LastName)" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? "; pstmt = connection.prepareStatement(sql); @@ -1086,7 +1108,7 @@ public void testLower() throws SQLException { */ @Test public void testPower() throws SQLException { - String sql = "SELECT POWER(ID,2)" + " FROM " + nameTable + String sql = "SELECT POWER(ID,2)" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? "; pstmt = connection.prepareStatement(sql); @@ -1117,10 +1139,16 @@ public void testPower() throws SQLException { public void testAllInOneQuery() throws SQLException { if (version >= SQL_SERVER_2012_VERSION) { - String sql = "select lower(FirstName), count(lastName) from " + nameTable + "where ID = ? and FirstName in" - + "(" + " select " + nameTable + ".FirstName from " + nameTable + " join " + phoneNumberTable - + " on " + nameTable + ".ID = " + phoneNumberTable + ".ID" + " where " + nameTable + ".ID = ? and " - + phoneNumberTable + ".ID = ?" + ")" + " group by FirstName " + " order by FirstName ASC"; + String sql = "select lower(FirstName), count(lastName) from " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + "where ID = ? and FirstName in" + "(" + + " select " + AbstractSQLGenerator.escapeIdentifier(nameTable) + ".FirstName from " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + " join " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + " on " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + ".ID = " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + ".ID" + " where " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + ".ID = ? and " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + ".ID = ?" + ")" + " group by FirstName " + + " order by FirstName ASC"; pstmt = connection.prepareStatement(sql); @@ -1147,7 +1175,8 @@ public void testAllInOneQuery() throws SQLException { */ @Test public void testQueryWithMultipleLineComments1() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/select top 100 c1 from " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/select top 100 c1 from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1167,7 +1196,7 @@ public void testQueryWithMultipleLineComments1() throws SQLException { public void testQueryWithMultipleLineComments2() throws SQLException { pstmt = connection .prepareStatement("/*/*te\nst*/ te/*test*/st /*te\nst*/*//*te/*test*/st*/select top 100 c1 from " - + charTable + " where c1 = ?"); + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1185,7 +1214,8 @@ public void testQueryWithMultipleLineComments2() throws SQLException { */ @Test public void testQueryWithMultipleLineCommentsInsert() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/insert /*test*/into " + charTable + " (c1) VALUES(?)"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/insert /*test*/into " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " (c1) VALUES(?)"); try { pstmt.getParameterMetaData(); @@ -1201,7 +1231,8 @@ public void testQueryWithMultipleLineCommentsInsert() throws SQLException { */ @Test public void testQueryWithMultipleLineCommentsUpdate() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/update /*test*/" + charTable + " set c1=123 where c1=?"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/update /*test*/" + + AbstractSQLGenerator.escapeIdentifier(charTable) + " set c1=123 where c1=?"); try { pstmt.getParameterMetaData(); @@ -1217,7 +1248,8 @@ public void testQueryWithMultipleLineCommentsUpdate() throws SQLException { */ @Test public void testQueryWithMultipleLineCommentsDeletion() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/delete /*test*/from " + charTable + " where c1=?"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/delete /*test*/from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1=?"); try { pstmt.getParameterMetaData(); @@ -1233,7 +1265,8 @@ public void testQueryWithMultipleLineCommentsDeletion() throws SQLException { */ @Test public void testQueryWithSingleLineComments1() throws SQLException { - pstmt = connection.prepareStatement("-- #test \n select top 100 c1 from " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement("-- #test \n select top 100 c1 from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1251,7 +1284,8 @@ public void testQueryWithSingleLineComments1() throws SQLException { */ @Test public void testQueryWithSingleLineComments2() throws SQLException { - pstmt = connection.prepareStatement("--#test\nselect top 100 c1 from " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement("--#test\nselect top 100 c1 from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1269,7 +1303,8 @@ public void testQueryWithSingleLineComments2() throws SQLException { */ @Test public void testQueryWithSingleLineComments3() throws SQLException { - pstmt = connection.prepareStatement("select top 100 c1\nfrom " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement( + "select top 100 c1\nfrom " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1287,7 +1322,8 @@ public void testQueryWithSingleLineComments3() throws SQLException { */ @Test public void testQueryWithSingleLineCommentsInsert() throws SQLException { - pstmt = connection.prepareStatement("--#test\ninsert /*test*/into " + charTable + " (c1) VALUES(?)"); + pstmt = connection.prepareStatement( + "--#test\ninsert /*test*/into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (c1) VALUES(?)"); try { pstmt.getParameterMetaData(); @@ -1303,7 +1339,8 @@ public void testQueryWithSingleLineCommentsInsert() throws SQLException { */ @Test public void testQueryWithSingleLineCommentsUpdate() throws SQLException { - pstmt = connection.prepareStatement("--#test\nupdate /*test*/" + charTable + " set c1=123 where c1=?"); + pstmt = connection.prepareStatement("--#test\nupdate /*test*/" + + AbstractSQLGenerator.escapeIdentifier(charTable) + " set c1=123 where c1=?"); try { pstmt.getParameterMetaData(); @@ -1319,7 +1356,8 @@ public void testQueryWithSingleLineCommentsUpdate() throws SQLException { */ @Test public void testQueryWithSingleLineCommentsDeletion() throws SQLException { - pstmt = connection.prepareStatement("--#test\ndelete /*test*/from " + charTable + " where c1=?"); + pstmt = connection.prepareStatement( + "--#test\ndelete /*test*/from " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1=?"); try { pstmt.getParameterMetaData(); @@ -1335,7 +1373,8 @@ public void testQueryWithSingleLineCommentsDeletion() throws SQLException { */ @Test public void testQueryWithSpaceAndEndCommentMarkInColumnName() throws SQLException { - pstmt = connection.prepareStatement("SELECT [c1*/someString withspace] from " + spaceTable); + pstmt = connection.prepareStatement( + "SELECT [c1*/someString withspace] from " + AbstractSQLGenerator.escapeIdentifier(spaceTable)); try { pstmt.getParameterMetaData(); @@ -1351,8 +1390,9 @@ public void testQueryWithSpaceAndEndCommentMarkInColumnName() throws SQLExceptio */ @Test public void testComplexQueryWithMultipleTables() throws SQLException { - pstmt = connection.prepareStatement("insert into " + charTable - + " (c1) select ? where not exists (select * from " + charTable2 + " where table2c1 = ?)"); + pstmt = connection.prepareStatement("insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + + " (c1) select ? where not exists (select * from " + AbstractSQLGenerator.escapeIdentifier(charTable2) + + " where table2c1 = ?)"); try { SQLServerParameterMetaData pMD = (SQLServerParameterMetaData) pstmt.getParameterMetaData(); @@ -1371,17 +1411,16 @@ public void testComplexQueryWithMultipleTables() throws SQLException { */ @AfterAll public static void dropTables() throws SQLException { - 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); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(nameTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(binaryTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(multipleTypesTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(spaceTable), stmt); if (null != rs) { rs.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 7aca2f875..e2ff2b703 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 @@ -28,15 +28,21 @@ 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.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class PreparedStatementTest extends AbstractTest { + + final String tableName = RandomUtil.getIdentifier("#update1"); + final String tableName2 = RandomUtil.getIdentifier("#update2"); + private void executeSQL(SQLServerConnection conn, String sql) throws SQLException { Statement stmt = conn.createStatement(); stmt.execute(sql); @@ -534,9 +540,6 @@ private void testStatementPoolingInternal(String mode) throws Exception { pstmt.getMoreResults(); // Make sure handle is updated. } } - System.out.println(String.format("Prep on first call: %s Query count:%s: %s of %s (%s)", - prepOnFirstCall, queryCount, testsWithHandleReuse, testCount, - (double) testsWithHandleReuse / (double) testCount)); } } } @@ -550,9 +553,11 @@ private void testStatementPoolingInternal(String mode) throws Exception { this.executeSQL(con, "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';"); // Test with missing handle failures (fake). - this.executeSQL(con, "CREATE TABLE #update1 (col INT);INSERT #update1 VALUES (1);"); - this.executeSQL(con, - "CREATE PROC #updateProc1 AS UPDATE #update1 SET col += 1; IF EXISTS (SELECT * FROM #update1 WHERE col % 5 = 0) RAISERROR(99586,16,1);"); + this.executeSQL(con, "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col INT);INSERT " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (1);"); + this.executeSQL(con, "CREATE PROC #updateProc1 AS UPDATE " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col += 1; IF EXISTS (SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col % 5 = 0) RAISERROR(99586,16,1);"); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc1")) { for (int i = 0; i < 100; ++i) { try { @@ -571,7 +576,8 @@ private void testStatementPoolingInternal(String mode) throws Exception { // test updated value, should be 1 + 100 = 101 // although executeUpdate() throws exception, update operation should be executed successfully. - try (ResultSet rs = con.createStatement().executeQuery("select * from #update1")) { + try (ResultSet rs = con.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + "")) { rs.next(); assertSame(101, rs.getInt(1)); } @@ -579,9 +585,11 @@ private void testStatementPoolingInternal(String mode) throws Exception { // Test batching with missing handle failures (fake). this.executeSQL(con, "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';"); - this.executeSQL(con, "CREATE TABLE #update2 (col INT);INSERT #update2 VALUES (1);"); - this.executeSQL(con, - "CREATE PROC #updateProc2 AS UPDATE #update2 SET col += 1; IF EXISTS (SELECT * FROM #update2 WHERE col % 5 = 0) RAISERROR(99586,16,1);"); + this.executeSQL(con, "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " (col INT);INSERT " + AbstractSQLGenerator.escapeIdentifier(tableName2) + " VALUES (1);"); + this.executeSQL(con, "CREATE PROC #updateProc2 AS UPDATE " + + AbstractSQLGenerator.escapeIdentifier(tableName2) + " SET col += 1; IF EXISTS (SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName2) + " WHERE col % 5 = 0) RAISERROR(99586,16,1);"); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc2")) { for (int i = 0; i < 100; ++i) { pstmt.addBatch(); @@ -605,7 +613,8 @@ private void testStatementPoolingInternal(String mode) throws Exception { // test updated value, should be 1 + 100 = 101 // although executeBatch() throws exception, update operation should be executed successfully. - try (ResultSet rs = con.createStatement().executeQuery("select * from #update2")) { + try (ResultSet rs = con.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName2) + "")) { rs.next(); assertSame(101, rs.getInt(1)); } 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 695155a9c..2daad278f 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 @@ -21,18 +21,20 @@ 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.SQLServerPreparedStatement; 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; @RunWith(JUnitPlatform.class) public class RegressionTest extends AbstractTest { - private static String tableName = "[ServerCursorPStmt]"; - private static String procName = "[ServerCursorProc]"; + private static String tableName; + private static String procName = RandomUtil.getIdentifier("ServerCursorProc"); /** * Tests select into stored proc @@ -49,32 +51,41 @@ public void testServerCursorPStmt() throws SQLException { String col3Value = "India"; String col3Lookup = "IN"; + tableName = RandomUtil.getIdentifier("ServerCursorPStmt"); + + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); + stmt.executeUpdate( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (1, 'CAN', 'Canada')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (2, 'USA', 'United States of America')"); 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 + "')"); + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (3, 'JPN', 'Japan')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(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"; + storedProcString = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @param varchar(3) AS SELECT col3 FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " WHERE col2 = @param"; } else { // On SQL Server - storedProcString = "CREATE PROCEDURE " + procName - + " @param varchar(3) AS SELECT col3 INTO #TMPTABLE FROM " + tableName + storedProcString = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @param varchar(3) AS SELECT col3 INTO #TMPTABLE FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col2 = @param SELECT col3 FROM #TMPTABLE"; } stmt.executeUpdate(storedProcString); // execute stored proc via pstmt - try (PreparedStatement pstmt = con.prepareStatement("EXEC " + procName + " ?", - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { + try (PreparedStatement pstmt = con.prepareStatement( + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + " ?", ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { pstmt.setString(1, col3Lookup); // should return 1 row @@ -88,6 +99,8 @@ public void testServerCursorPStmt() throws SQLException { TestResource.getResource("R_valueNotMatch") + rs.getString(1) + ", " + col3Value); } } + } finally { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -103,23 +116,28 @@ public void testSelectIntoUpdateCount() throws SQLException { // Azure does not do SELECT INTO if (!DBConnection.isSqlAzure(con)) { - final String tableName = "[#SourceTableForSelectInto]"; + tableName = RandomUtil.getIdentifier("[#SourceTableForSelectInto]]"); try (Statement stmt = con.createStatement()) { - stmt.executeUpdate("CREATE TABLE " + tableName + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(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 " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (1, 'CAN', 'Canada')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (2, 'USA', 'United States of America')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (3, 'JPN', 'Japan')"); // expected values int numRowsToCopy = 2; - try (PreparedStatement ps = con - .prepareStatement("SELECT * INTO #TMPTABLE FROM " + tableName + " WHERE col1 <= ?")) { + try (PreparedStatement ps = con.prepareStatement("SELECT * INTO #TMPTABLE FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 <= ?")) { ps.setInt(1, numRowsToCopy); int updateCount = ps.executeUpdate(); assertEquals(numRowsToCopy, updateCount, TestResource.getResource("R_incorrectUpdateCount")); + } finally { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -141,16 +159,16 @@ public void testUpdateQuery() throws SQLException { String sql; JDBCType[] targets = {JDBCType.INTEGER, JDBCType.SMALLINT}; int rows = 3; - final String tableName = "[updateQuery]"; + tableName = RandomUtil.getIdentifier("[updateQuery]"); - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate( - "CREATE TABLE " + tableName + " (" + "c1 int null," + "PK int NOT NULL PRIMARY KEY" + ")"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (" + + "c1 int null," + "PK int NOT NULL PRIMARY KEY" + ")"); /* * populate table */ - sql = "insert into " + tableName + " values(" + "?,?" + ")"; + sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(" + "?,?" + ")"; try (PreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, con.getHoldability())) { @@ -163,7 +181,7 @@ public void testUpdateQuery() throws SQLException { /* * Update table */ - sql = "update " + tableName + " SET c1= ? where PK =1"; + sql = "update " + AbstractSQLGenerator.escapeIdentifier(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)) { @@ -177,15 +195,16 @@ public void testUpdateQuery() throws SQLException { /* * Verify */ - try (ResultSet rs = stmt.executeQuery("select * from " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); assertEquals(rs.getInt(1), 8, "Value mismatch"); + } finally { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } - private String xmlTableName = "try_SQLXML_Table"; - /** * Tests XML query * @@ -198,16 +217,18 @@ public void testXmlQuery() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - dropTables(stmt); + TestUtils.dropTableIfExists(tableName, stmt); createTable(stmt); - String sql = "UPDATE " + xmlTableName + " SET [c2] = ?, [c3] = ?"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { + tableName = RandomUtil.getIdentifier("try_SQLXML_Table"); + String sql = "UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET [c2] = ?, [c3] = ?"; + try (SQLServerPreparedStatement 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, Types.SQLXML); pstmt.setObject(2, null); @@ -218,17 +239,16 @@ public void testXmlQuery() throws SQLException { pstmt.setObject(1, null); pstmt.setObject(2, null, Types.SQLXML); pstmt.executeUpdate(); + } finally { + TestUtils.dropTableIfExists(tableName, stmt); } } } - private void dropTables(Statement stmt) throws SQLException { - stmt.executeUpdate("if object_id('" + xmlTableName + "','U') is not null" + " drop table " + xmlTableName); - } - private void createTable(Statement stmt) throws SQLException { - String sql = "CREATE TABLE " + xmlTableName + " ([c1] int, [c2] xml, [c3] xml)"; + String sql = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1] int, [c2] xml, [c3] xml)"; stmt.execute(sql); } @@ -238,7 +258,7 @@ public static void terminate() throws SQLException { try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(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 ab3054963..b04a143ea 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 @@ -70,8 +70,7 @@ public class TCAttentionHandling { + " It is particularly long so that we will get a multipacket TDS response back from the server." + " This is a test string." + " This is a test string." + " This is a test string." + " This is a test string." + " This is a test string." + " This is a test string."; - String tableN = RandomUtil.getIdentifier("TCAttentionHandling"); - String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); + String tableName = RandomUtil.getIdentifier("TCAttentionHandling"); @BeforeEach public void init() throws Exception { @@ -79,13 +78,13 @@ public void init() throws Exception { con.setAutoCommit(false); try (Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT PRIMARY KEY, col2 VARCHAR(" - + TEST_STRING.length() + "))"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(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.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1, col2) VALUES (" + i + ", '" + TEST_STRING + "')"); } con.commit(); } @@ -96,7 +95,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} } } @@ -112,7 +111,8 @@ public void testCancelBeforeExecute() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { stmt.cancel(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { int numSelectedRows = 0; while (rs.next()) ++numSelectedRows; @@ -134,8 +134,9 @@ public void testCancelBeforeExecute() throws Exception { */ @Test public void testErrorInRequest() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); PreparedStatement ps = con - .prepareStatement("UPDATE " + tableName + " SET col2 = ? WHERE col1 = ?")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement ps = con.prepareStatement("UPDATE " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col2 = ? WHERE col1 = ?")) { ps.setString(1, TEST_STRING); for (int i = 0; i < MIN_TABLE_ROWS; i++) { ps.setInt(2, i); @@ -233,7 +234,8 @@ public void testCancelLongResponse() throws Exception { } try (ResultSet rs = stmt.executeQuery( - "SELECT " + "a.col1, a.col2 FROM " + tableName + " a CROSS JOIN " + tableName + " b")) { + "SELECT " + "a.col1, a.col2 FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " a CROSS JOIN " + AbstractSQLGenerator.escapeIdentifier(tableName) + " b")) { // Scan the first MIN_TABLE_ROWS rows int numSelectedRows = 0; @@ -311,8 +313,8 @@ public void testCancelBlockedResponse() throws Exception { // and leave it non-responsive for now... conLock.setAutoCommit(false); try (Statement stmtLock = conLock.createStatement()) { - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(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 @@ -339,7 +341,8 @@ public void testCancelBlockedResponse() throws Exception { 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)) { + try (ResultSet rs = stmt.executeQuery( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { // Time how long it takes for execution to be cancelled... long elapsedMillis = -System.currentTimeMillis(); @@ -402,8 +405,8 @@ public void testCancelBlockedResponsePS() throws Exception { // and leave it non-responsive for now... conLock.setAutoCommit(false); try (Statement stmtLock = conLock.createStatement()) { - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(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 @@ -426,7 +429,8 @@ public void testCancelBlockedResponsePS() throws Exception { // // Need to use adaptive response buffering when executing the statement. // Otherwise, we would block in executeQuery()... - try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM " + tableName, + try (PreparedStatement stmt = con.prepareStatement( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName), SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); try (ResultSet rs = stmt.executeQuery()) { @@ -496,8 +500,8 @@ public void testCancelBlockedCursoredResponse() throws Exception { // and leave it non-responsive for now... conLock.setAutoCommit(false); try (Statement stmtLock = conLock.createStatement()) { - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(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 @@ -515,7 +519,8 @@ public void testCancelBlockedCursoredResponse() throws Exception { con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); } - try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM " + tableName, + try (PreparedStatement stmt = con.prepareStatement( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(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. @@ -577,7 +582,8 @@ public void testCancelAfterResponse() throws Exception { int numSelectedRows; try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { numSelectedRows = 0; while (rs.next()) ++numSelectedRows; @@ -589,7 +595,8 @@ public void testCancelAfterResponse() throws Exception { stmt.cancel(); // Verify that the query can be re-executed without error - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { numSelectedRows = 0; while (rs.next()) ++numSelectedRows; @@ -606,18 +613,19 @@ public void testCancelAfterResponse() throws Exception { public void testCancelGetOutParams() throws Exception { // Use small packet size to force OUT params to span multiple packets // so that cancelling execution from the same thread will work. - String name = RandomUtil.getIdentifier("p1"); - final String procName = AbstractSQLGenerator.escapeIdentifier(name); + final String procName = RandomUtil.getIdentifier("p1"); try (Connection con = DriverManager.getConnection(connectionString + ";packetSize=512"); Statement stmt = con.createStatement()) { try { - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(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"); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?, ?)}")) { + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @arg1 CHAR(512) OUTPUT, " + " @arg2 CHAR(512) OUTPUT, " + + " @arg3 CHAR(512) OUTPUT " + "AS " + "BEGIN " + " SET @arg1='hi' " + + " SET @arg2='there' " + " SET @arg3='!' " + "END"); + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?, ?)}")) { ((SQLServerStatement) cstmt).setResponseBuffering("adaptive"); cstmt.registerOutParameter(1, Types.CHAR); cstmt.registerOutParameter(2, Types.CHAR); @@ -646,7 +654,7 @@ public void testCancelGetOutParams() throws Exception { // Reexecute to prove CS is still good after last cancel cstmt.execute(); } - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } } @@ -710,7 +718,8 @@ void start(final Connection con) { public void run() { ++numExecuteTries; - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt.executeQuery( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) ++numExecuteSuccesses; @@ -880,10 +889,8 @@ public void testCloseOnCompletion() throws Exception { @Nested public class TCStatement { - String tableNTemp = RandomUtil.getIdentifier("TCStatement1"); - private final String table1Name = AbstractSQLGenerator.escapeIdentifier(tableNTemp); - String table2NameTemp = RandomUtil.getIdentifier("TCStatement2"); - private final String table2Name = AbstractSQLGenerator.escapeIdentifier(table2NameTemp); + private final String table1Name = RandomUtil.getIdentifier("TCStatement1"); + private final String table2Name = RandomUtil.getIdentifier("TCStatement2"); /** * test statement.closeOnCompltetion method @@ -953,16 +960,19 @@ public void testConsecutiveQueries() throws Exception { } try { - TestUtils.dropTableIfExists(table1Name, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1Name), stmt); } catch (SQLException e) {} try { - TestUtils.dropTableIfExists(table2Name, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); } catch (SQLException e) {} - stmt.executeUpdate("CREATE TABLE " + table1Name + " (col1 INT PRIMARY KEY)"); - stmt.executeUpdate("CREATE TABLE " + table2Name + " (col1 INT PRIMARY KEY)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table1Name) + + " (col1 INT PRIMARY KEY)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (col1 INT PRIMARY KEY)"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + table2Name)) {} catch (Exception e) { + try (ResultSet rs = stmt.executeQuery( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(table2Name))) {} catch (Exception e) { assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); } } @@ -1055,8 +1065,8 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - TestUtils.dropTableIfExists(table1Name, stmt); - TestUtils.dropTableIfExists(table2Name, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1Name), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); } catch (SQLException e) {} } } @@ -1064,8 +1074,7 @@ public void terminate() throws Exception { @Nested public class TCStatementCallable { - String name = RandomUtil.getIdentifier("p1"); - String procName = AbstractSQLGenerator.escapeIdentifier(name); + String procName = RandomUtil.getIdentifier("p1"); /** * Tests CallableStatementMethods on jdbc41 @@ -1078,10 +1087,10 @@ public void testJdbc41CallableStatementMethods() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - String query = "create procedure " + procName + " @col1Value varchar(512) OUTPUT," - + " @col2Value int OUTPUT," + " @col3Value float OUTPUT," + " @col4Value decimal(10,5) OUTPUT," - + " @col5Value uniqueidentifier OUTPUT," + " @col6Value xml OUTPUT," - + " @col7Value varbinary(max) OUTPUT," + " @col8Value text OUTPUT," + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col1Value varchar(512) OUTPUT," + " @col2Value int OUTPUT," + " @col3Value float OUTPUT," + + " @col4Value decimal(10,5) OUTPUT," + " @col5Value uniqueidentifier OUTPUT," + + " @col6Value xml OUTPUT," + " @col7Value varbinary(max) OUTPUT," + " @col8Value text OUTPUT," + " @col9Value ntext OUTPUT," + " @col10Value varbinary(max) OUTPUT," + " @col11Value date OUTPUT," + " @col12Value time OUTPUT," + " @col13Value datetime2 OUTPUT," + " @col14Value datetimeoffset OUTPUT," + " @col15Value decimal(10,10) OUTPUT," @@ -1098,7 +1107,8 @@ public void testJdbc41CallableStatementMethods() throws Exception { // Test JDBC 4.1 methods for CallableStatement try (CallableStatement cstmt = conn - .prepareCall("{call " + procName + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}")) { + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}")) { cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); cstmt.registerOutParameter(2, java.sql.Types.INTEGER); cstmt.registerOutParameter(3, java.sql.Types.FLOAT); @@ -1212,7 +1222,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1223,10 +1233,8 @@ public void terminate() throws Exception { @Nested public class TCStatementParam { - String tableNameTemp = RandomUtil.getIdentifier("TCStatementParam"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); - String procNameTemp = "TCStatementParam"; - private final String procName = AbstractSQLGenerator.escapeIdentifier(procNameTemp); + private final String tableName = RandomUtil.getIdentifier("TCStatementParam"); + private final String procName = RandomUtil.getIdentifier("TCStatementParam"); /** * @@ -1244,7 +1252,7 @@ public void testStatementOutParamGetsTwice() throws Exception { log.fine("testStatementOutParamGetsTwice threw: " + e.getMessage()); } - stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); try (ResultSet rs = stmt.getResultSet()) { @@ -1256,7 +1264,8 @@ public void testStatementOutParamGetsTwice() throws Exception { } } - try (CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?,?)}")) { cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1284,10 +1293,11 @@ public void testStatementOutParamGetsTwice() throws Exception { public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " ( @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 + " (?,?, ?, ?)}")) { + try (CallableStatement cstmt = con.prepareCall( + "{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?,?, ?, ?)}")) { cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1317,10 +1327,11 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { public void testStatementOutParamGetsTwiceInOut() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " ( @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 + " (?,?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?,?)}")) { cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("1"), Types.SMALLINT); cstmt.setObject(3, Short.valueOf("100"), Types.SMALLINT); @@ -1347,16 +1358,20 @@ public void testResultSetParams() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); 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 + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hello')"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hi')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col1=@col1Value SET @col2Value='hi' END"; stmt.execute(query); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?)}")) { cstmt.setInt(1, 0); cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); try (ResultSet rs = cstmt.executeQuery()) { @@ -1378,16 +1393,20 @@ public void testResultSetNullParams() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hello')"); 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 + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hi')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col1=@col1Value SET @col2Value='hi' END"; stmt.execute(query); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?)}")) { cstmt.setInt(1, 0); try { cstmt.getInt(2); @@ -1408,21 +1427,24 @@ public void testFailedToResumeTransaction() throws Exception { 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)"); - try (PreparedStatement ps = con - .prepareStatement("BEGIN TRAN " + "Insert into " + tableName + " values(4) " + "ROLLBACK")) {} + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int primary key)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(1)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(2)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(3)"); + try (PreparedStatement ps = con.prepareStatement("BEGIN TRAN " + "Insert into " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(4) " + "ROLLBACK")) {} con.setAutoCommit(false); - try (PreparedStatement ps2 = con.prepareStatement("Insert into " + tableName + " values('a')")) { + try (PreparedStatement ps2 = con.prepareStatement( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values('a')")) { try { ps2.execute(); } catch (SQLException e) {} try { - stmt.executeUpdate("Insert into " + tableName + " values(4)"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(4)"); } catch (SQLException ex) {} } } @@ -1437,15 +1459,18 @@ public void testResultSetErrors() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hello')"); 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 + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hi')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from somenonexistanttable where col1=@col1Value SET @col2Value='hi' END"; stmt.execute(query); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?)}")) { cstmt.setInt(1, 0); cstmt.registerOutParameter(2, Types.VARCHAR); @@ -1466,13 +1491,15 @@ public void testRowError() throws Exception { 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( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int primary key)"); + stmt.executeUpdate("insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0)"); + stmt.executeUpdate("insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(1)"); + stmt.executeUpdate("insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(2)"); stmt.execute( - "create procedure " + procName + " @col1Value int AS " + " BEGIN " + " SELECT col1 FROM " - + tableName + " WITH (UPDLOCK) WHERE (col1 = @col1Value) " + " END"); + "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col1Value int AS " + + " BEGIN " + " SELECT col1 FROM " + AbstractSQLGenerator.escapeIdentifier(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 @@ -1488,7 +1515,8 @@ public void testRowError() throws Exception { // locking it for update. try (Connection testConn1 = DriverManager.getConnection(connectionString)) { testConn1.setAutoCommit(false); - try (CallableStatement cstmt = testConn1.prepareCall("{call " + procName + "(?)}")) { + try (CallableStatement cstmt = testConn1 + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?)}")) { cstmt.setInt(1, row); // enable isCloseOnCompletion @@ -1511,8 +1539,8 @@ public void testRowError() throws Exception { try (Statement stmt2 = testConn2.createStatement()) { stmt2.executeUpdate("SET LOCK_TIMEOUT 0"); - try (CallableStatement cstmt2 = testConn2 - .prepareCall("SELECT col1 FROM " + tableName + " WITH (UPDLOCK)")) { + try (CallableStatement cstmt2 = testConn2.prepareCall("SELECT col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WITH (UPDLOCK)")) { // Verify that the result set can be closed after // the lock timeout error @@ -1556,8 +1584,8 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1567,8 +1595,7 @@ public void terminate() throws Exception { @Nested public class TCSparseColumnSetAndNBCROW { - String temp = RandomUtil.getIdentifier("TCStatementSparseColumnSetAndNBCROW"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(temp); + private final String tableName = RandomUtil.getIdentifier("TCStatementSparseColumnSetAndNBCROW"); private Connection createConnectionAndPopulateData() throws Exception { SQLServerDataSource ds = new SQLServerDataSource(); @@ -1580,9 +1607,9 @@ private Connection createConnectionAndPopulateData() throws Exception { Statement stmt = con.createStatement(); - stmt.executeUpdate("CREATE TABLE " + tableName + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(col1_int int PRIMARY KEY IDENTITY(1,1), col2_varchar varchar(200), col3_varchar varchar(20) SPARSE NULL, col4_smallint smallint SPARSE NULL, col5_xml XML COLUMN_SET FOR ALL_SPARSE_COLUMNS, col6_nvarcharMax NVARCHAR(MAX), col7_varcharMax VARCHAR(MAX))"); - stmt.executeUpdate("INSERT INTO " + tableName + " DEFAULT VALUES"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " DEFAULT VALUES"); assertTrue(con != null, "connection is null"); return con; @@ -1593,7 +1620,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1616,7 +1643,7 @@ public void testNBCROWNullsForLOBs() throws Exception { 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; + + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); @@ -1648,7 +1675,7 @@ public void testSparseColumnSetValues() throws Exception { 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; + + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); @@ -1687,7 +1714,7 @@ public void testSparseColumnSetIndex() throws Exception { 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; + + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); @@ -1726,7 +1753,7 @@ public void testSparseColumnSetForException() throws Exception { SQLServerResultSetMetaData rsmd; try (Connection con = createConnectionAndPopulateData(); Statement stmt = con.createStatement()) { - String selectQuery = "SELECT * FROM " + tableName; + String selectQuery = "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); @@ -1738,7 +1765,8 @@ public void testSparseColumnSetForException() throws Exception { stmt.close(); rsmd.isSparseColumnSet(1); } - try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); con.close(); rsmd.isSparseColumnSet(1); @@ -1765,10 +1793,11 @@ public void testNBCRowForAllNulls() throws Exception { try (Connection con = ds.getConnection(); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} - String createTableQuery = "CREATE TABLE " + tableName + "(col1 int PRIMARY KEY IDENTITY(1,1)"; + String createTableQuery = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1 int PRIMARY KEY IDENTITY(1,1)"; int noOfColumns = 128; for (int i = 2; i <= noOfColumns; i++) { @@ -1776,8 +1805,10 @@ public void testNBCRowForAllNulls() throws Exception { } createTableQuery += ")"; stmt.executeUpdate(createTableQuery); - stmt.executeUpdate("INSERT INTO " + tableName + " DEFAULT VALUES"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + stmt.executeUpdate( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " DEFAULT VALUES"); + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); // test that all columns except the first one are null @@ -1816,11 +1847,12 @@ public void testNBCROWWithRandomAccess() throws Exception { try (Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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)"; + String createTableQuery = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1 int PRIMARY KEY IDENTITY(1,1)"; for (int i = 2; i <= noOfColumns; i++) { createTableQuery = createTableQuery + ", col" + i + " int"; @@ -1828,7 +1860,7 @@ public void testNBCROWWithRandomAccess() throws Exception { createTableQuery += ")"; stmt.executeUpdate(createTableQuery); - stmt.executeUpdate("TRUNCATE TABLE " + tableName); + stmt.executeUpdate("TRUNCATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName)); // randomly generate columns whose values would be set to a non null value nonNullColumns = new ArrayList<>(); @@ -1844,7 +1876,7 @@ public void testNBCROWWithRandomAccess() throws Exception { } // construct the insert query - String insertQuery = "INSERT INTO " + tableName + "("; + String insertQuery = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + "("; String values = " VALUES("; for (int i = 1; i < nonNullColumns.size(); i++) { insertQuery = insertQuery + "col" + nonNullColumns.get(i); @@ -1861,7 +1893,8 @@ public void testNBCROWWithRandomAccess() throws Exception { // if there are no non-null columns if (nonNullColumns.size() == 1) - insertQuery = "INSERT INTO " + tableName + " DEFAULT VALUES"; + insertQuery = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " DEFAULT VALUES"; log.fine("INSEER Query:" + insertQuery); // populate the table by executing the insert query @@ -1871,7 +1904,8 @@ public void testNBCROWWithRandomAccess() throws Exception { } try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { // Try accessing rows and columns randomly for 10 times for (int j = 0; j < 10; j++) { @@ -2073,10 +2107,10 @@ public void testClosedConnection() throws Exception { public class TCUpdateCountWithTriggers { private static final int NUM_ROWS = 3; - private final String tableName = "[TCUpdateCountWithTriggersTable1]"; - private final String table2Name = "[TCUpdateCountWithTriggersTable2]"; - private final String sprocName = "[TCUpdateCountWithTriggersProc]"; - private final String triggerName = "[TCUpdateCountWithTriggersTrigger]"; + private final String tableName = RandomUtil.getIdentifier("TCUpdateCountWithTriggersTable1"); + private final String table2Name = RandomUtil.getIdentifier("TCUpdateCountWithTriggersTable2"); + private final String sprocName = RandomUtil.getIdentifier("TCUpdateCountWithTriggersProc"); + private final String triggerName = RandomUtil.getIdentifier("TCUpdateCountWithTriggersTrigger"); @BeforeEach public void setup() throws Exception { @@ -2085,27 +2119,36 @@ public void setup() throws Exception { try (Statement stmt = con.createStatement()) { try { - stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName - + "') drop trigger " + triggerName); + stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + + TestUtils.escapeSingleQuotes((triggerName)) + "') drop trigger " + + AbstractSQLGenerator.escapeIdentifier(triggerName)); } catch (SQLException e) { throw new SQLException(e); } - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT PRIMARY KEY)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 INT PRIMARY KEY)"); for (int i = 0; i < NUM_ROWS; i++) - stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(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 " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (NAME VARCHAR(100), col2 int identity(1,1) primary key)"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (NAME) VALUES ('BLAH')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (NAME) VALUES ('FNORD')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(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 " + AbstractSQLGenerator.escapeIdentifier(sprocName) + " AS " + + "Begin " + " Update " + AbstractSQLGenerator.escapeIdentifier(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 " + AbstractSQLGenerator.escapeIdentifier(triggerName) + " ON " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " FOR DELETE AS " + "Begin " + + "Declare @l_retstat Integer " + "Execute @l_retstat = " + + AbstractSQLGenerator.escapeIdentifier(sprocName) + " " + "If (@l_retstat <> 0) " + + "Begin " + " Rollback Transaction " + "End " + "End"); } con.commit(); @@ -2121,7 +2164,8 @@ public void setup() throws Exception { public void testLastUpdateCountTrue() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); - PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?")) { + PreparedStatement ps = con.prepareStatement( + "DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 = ?")) { ps.setInt(1, 1); int updateCount = ps.executeUpdate(); @@ -2140,7 +2184,8 @@ public void testLastUpdateCountTrue() throws Exception { public void testLastUpdateCountFalse() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=false"); - PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?")) { + PreparedStatement ps = con.prepareStatement( + "DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 = ?")) { ps.setInt(1, 1); int updateCount = ps.executeUpdate(); @@ -2159,9 +2204,10 @@ public void testLastUpdateCountFalse() throws Exception { public void testPreparedStatementInsertExecInsert() throws Exception { 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'")) { + PreparedStatement ps = con.prepareStatement("INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1) VALUES (" + (NUM_ROWS + 1) + + "); " + "EXEC " + AbstractSQLGenerator.escapeIdentifier(sprocName) + "; " + "UPDATE " + + AbstractSQLGenerator.escapeIdentifier(table2Name) + " SET NAME = 'FISH'")) { int updateCount = ps.executeUpdate(); @@ -2181,11 +2227,13 @@ public void testStatementInsertExecInsert() throws Exception { 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'"); + int updateCount = stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1) VALUES (" + (NUM_ROWS + 1) + "); " + "EXEC " + + AbstractSQLGenerator.escapeIdentifier(sprocName) + "; " + "UPDATE " + + AbstractSQLGenerator.escapeIdentifier(table2Name) + " SET NAME = 'FISH'"); // updateCount should be from the INSERT, - // which should have affected 1 (new) row in tableName. + // which should have affected 1 (new) row in AbstractSQLGenerator.escapeIdentifier(tableName). assertEquals(updateCount, 1, "Wrong update count"); } } @@ -2195,9 +2243,9 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(table2Name, stmt); - TestUtils.dropProcedureIfExists(sprocName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(sprocName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -2207,8 +2255,7 @@ public void terminate() throws Exception { @Nested public class TCUpdateCountAfterRaiseError { - String tableNameTemp = RandomUtil.getIdentifier("TCUpdateCountAfterRaiseError"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); + private final String tableName = RandomUtil.getIdentifier("TCUpdateCountAfterRaiseError"); private final String triggerName = "TCUpdateCountAfterRaiseErrorTrigger"; private final int NUM_ROWS = 3; private final String errorMessage50001InSqlAzure = "Error 50001, severity 17, state 1 was raised, but no message with that error number was found in sys.messages. If error is larger than 50000, make sure the user-defined message is added using sp_addmessage."; @@ -2220,14 +2267,17 @@ public void setup() throws Exception { try (Statement stmt = con.createStatement()) { try { - stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName - + "') drop trigger " + triggerName); + stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + + AbstractSQLGenerator.escapeIdentifier(triggerName) + "') drop trigger " + + AbstractSQLGenerator.escapeIdentifier(triggerName)); } catch (SQLException e) { System.out.println(e.toString()); } - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT primary key)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 INT primary key)"); for (int i = 0; i < NUM_ROWS; i++) - stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1) VALUES (" + i + ")"); // Skip adding message for 50001 if the target server is SQL Azure, because SQL Azure does not // support @@ -2244,9 +2294,10 @@ public void setup() throws Exception { } } - stmt.executeUpdate( - "CREATE TRIGGER " + triggerName + " ON " + tableName + " FOR INSERT AS BEGIN DELETE FROM " - + tableName + " WHERE col1 = 1 RAISERROR(50001, 17, 1) END"); + stmt.executeUpdate("CREATE TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + " ON " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " FOR INSERT AS BEGIN DELETE FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + + " WHERE col1 = 1 RAISERROR(50001, 17, 1) END"); } con.commit(); } @@ -2261,8 +2312,10 @@ public void setup() throws Exception { public void testUpdateCountAfterRaiseError() throws Exception { 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)) { + PreparedStatement pstmt = con + .prepareStatement("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " SET col1 = 5 WHERE col1 = 2 RAISERROR(50001, 17, 1) SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName))) { // enable isCloseOnCompletion try { @@ -2315,7 +2368,8 @@ public void testUpdateCountAfterRaiseError() throws Exception { public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = false"); - PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)")) { + PreparedStatement pstmt = con.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (5)")) { int updateCount = pstmt.executeUpdate(); assertEquals(updateCount, 1, "First result: should have been 1 row deleted"); @@ -2343,7 +2397,8 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exce 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"); - try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { int rowCount = 0; while (rs.next()) ++rowCount; @@ -2362,7 +2417,8 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exce public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); - PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)")) { + PreparedStatement pstmt = con.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (5)")) { try { pstmt.executeUpdate(); @@ -2391,7 +2447,8 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Excep assertEquals(pstmt.getUpdateCount(), 1, "Second result: wrong number of rows inserted"); } - try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { int rowCount = 0; while (rs.next()) ++rowCount; @@ -2405,7 +2462,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -2415,8 +2472,7 @@ public void terminate() throws Exception { @Nested public class TCNocount { - final String tableNameTemp = RandomUtil.getIdentifier("TCNoCount"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); + private final String tableName = RandomUtil.getIdentifier("TCNoCount"); private static final int NUM_ROWS = 3; @@ -2432,9 +2488,11 @@ public void setup() throws Exception { } catch (Exception e) { throw new SQLException(TestResource.getResource("R_unexpectedException"), e); } - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT primary key)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 INT primary key)"); for (int i = 0; i < NUM_ROWS; i++) - stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1) VALUES (" + i + ")"); assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); } @@ -2453,8 +2511,9 @@ public void testNoCountWithExecute() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); Statement stmt = con.createStatement();) { - boolean isResultSet = stmt.execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" - + (NUM_ROWS + 1) + ")\n" + "select 1"); + boolean isResultSet = stmt + .execute("set nocount on\n" + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); assertEquals(true, isResultSet, "execute() said first result was an update count"); @@ -2475,7 +2534,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(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 3f51817d8..b0b098850 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java @@ -79,7 +79,6 @@ public static void setup() throws Exception { info.setProperty("keyStoreLocation", jksPaths[0]); info.setProperty("keyStoreSecret", secretstrJks); } - logger.info("In AbstractTest:setup"); try { Assertions.assertNotNull(connectionString, "Connection String should not be null");