diff --git a/build.gradle b/build.gradle index aa88d5d71..d3b7e8332 100644 --- a/build.gradle +++ b/build.gradle @@ -88,16 +88,16 @@ dependencies { 'com.microsoft.azure:azure-keyvault-webkey:1.2.0', 'com.microsoft.rest:client-runtime:1.6.5', 'com.microsoft.azure:adal4j:1.6.3' - testCompile 'org.junit.platform:junit-platform-console:1.3.2', - 'org.junit.platform:junit-platform-commons:1.3.2', - 'org.junit.platform:junit-platform-engine:1.3.2', - 'org.junit.platform:junit-platform-launcher:1.3.2', - 'org.junit.platform:junit-platform-runner:1.3.2', + testCompile 'org.junit.platform:junit-platform-console:1.4.0', + 'org.junit.platform:junit-platform-commons:1.4.0', + 'org.junit.platform:junit-platform-engine:1.4.0', + 'org.junit.platform:junit-platform-launcher:1.4.0', + 'org.junit.platform:junit-platform-runner:1.4.0', 'org.junit.platform:junit-platform-surefire-provider:1.3.2', - 'org.junit.jupiter:junit-jupiter-api:5.3.2', - 'org.junit.jupiter:junit-jupiter-engine:5.3.2', - 'com.zaxxer:HikariCP:3.2.0', - 'org.apache.commons:commons-dbcp2:2.5.0', - 'org.slf4j:slf4j-nop:1.7.25', - 'org.eclipse.gemini.blueprint:gemini-blueprint-mock:2.0.0.RELEASE' + 'org.junit.jupiter:junit-jupiter-api:5.4.0', + 'org.junit.jupiter:junit-jupiter-engine:5.4.0', + 'com.zaxxer:HikariCP:3.3.1', + 'org.apache.commons:commons-dbcp2:2.6.0', + 'org.slf4j:slf4j-nop:1.7.26', + 'org.eclipse.gemini.blueprint:gemini-blueprint-mock:2.1.0.RELEASE' } diff --git a/pom.xml b/pom.xml index 12c3c243a..3df39e7b0 100644 --- a/pom.xml +++ b/pom.xml @@ -39,35 +39,44 @@ UTF-8 - 1.3.2 - 5.3.2 + + 1.2.0 + 1.6.3 + 1.6.5 4.3.1 + + [1.3.2,1.4.0] + 5.4.0 + 3.3.1 + 2.6.0 + 1.7.26 + 2.1.0.RELEASE com.microsoft.azure azure-keyvault - 1.2.0 + ${azure.keyvault.version} true com.microsoft.azure azure-keyvault-webkey - 1.2.0 + ${azure.keyvault.version} true com.microsoft.azure adal4j - 1.6.3 + ${azure.adal4j.version} true com.microsoft.rest client-runtime - 1.6.5 + ${rest.client.version} true @@ -137,25 +146,25 @@ com.zaxxer HikariCP - 3.2.0 + ${hikaricp.version} test org.apache.commons commons-dbcp2 - 2.5.0 + ${dbcp2.version} test org.slf4j slf4j-nop - 1.7.25 + ${slf4j.nop.version} test org.eclipse.gemini.blueprint gemini-blueprint-mock - 2.0.0.RELEASE + ${gemini.mock.version} test @@ -407,6 +416,7 @@ 3.0.0 true + mssql.googlecode.* diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java index fab2ff503..794253372 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java @@ -47,7 +47,6 @@ import java.util.logging.Level; import javax.sql.RowSet; -import javax.sql.XAConnection; import microsoft.sql.DateTimeOffset; @@ -888,6 +887,7 @@ private void writeTypeInfo(TDSWriter tdsWriter, int srcJdbcType, int srcScale, i } break; + case java.sql.Types.FLOAT: case java.sql.Types.DOUBLE: // (FLT8TYPE) 0x3E if (!srcNullable) { tdsWriter.writeByte(TDSType.FLOAT8.byteValue()); @@ -1244,6 +1244,7 @@ private String getDestTypeFromSrcType(int srcColIndx, int destColIndx, case java.sql.Types.TINYINT: return "tinyint"; + case java.sql.Types.FLOAT: case java.sql.Types.DOUBLE: return "float"; @@ -1929,6 +1930,7 @@ private void writeNullToTdsWriter(TDSWriter tdsWriter, int srcJdbcType, case java.sql.Types.BIGINT: case java.sql.Types.REAL: case java.sql.Types.DOUBLE: + case java.sql.Types.FLOAT: case java.sql.Types.DECIMAL: case java.sql.Types.NUMERIC: case java.sql.Types.TIMESTAMP: @@ -2051,6 +2053,17 @@ else if (null != sourceCryptoMeta) { } break; + case java.sql.Types.FLOAT: + if (null == colValue) { + writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming); + } else { + if (bulkNullable) { + tdsWriter.writeByte((byte) 0x08); + } + tdsWriter.writeDouble((float) colValue); + } + break; + case java.sql.Types.DOUBLE: if (null == colValue) { writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming); @@ -2701,6 +2714,7 @@ private Object readColumnFromResultSet(int srcColOrdinal, int srcJdbcType, boole case java.sql.Types.TINYINT: case java.sql.Types.DOUBLE: case java.sql.Types.REAL: + case java.sql.Types.FLOAT: return sourceResultSet.getObject(srcColOrdinal); case microsoft.sql.Types.MONEY: @@ -3334,12 +3348,11 @@ private byte[] normalizedValue(JDBCType destJdbcType, Object value, JDBCType src return ((String) value).getBytes(UTF_16LE); case REAL: - case FLOAT: - Float floatValue = (value instanceof String) ? Float.parseFloat((String) value) : (Float) value; return ByteBuffer.allocate((Float.SIZE / Byte.SIZE)).order(ByteOrder.LITTLE_ENDIAN) .putFloat(floatValue).array(); - + + case FLOAT: case DOUBLE: Double doubleValue = (value instanceof String) ? Double.parseDouble((String) value) : (Double) value; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index b779bed2e..633587a38 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -140,7 +140,12 @@ public class SQLServerConnection implements ISQLServerConnection, java.io.Serial private String originalHostNameInCertificate = null; + final int ENGINE_EDITION_FOR_SQL_AZURE = 5; + final int ENGINE_EDITION_FOR_SQL_AZURE_DW = 6; + final int ENGINE_EDITION_FOR_SQL_AZURE_MI = 8; + private Boolean isAzure = null; private Boolean isAzureDW = null; + private Boolean isAzureMI = null; private SharedTimer sharedTimer; @@ -3164,16 +3169,10 @@ public void rollback() throws SQLServerException { public void abort(Executor executor) throws SQLException { loggerExternal.entering(getClassNameLogging(), "abort", executor); - // nop if connection is closed + // no-op if connection is closed if (isClosed()) return; - if (null == executor) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidArgument")); - Object[] msgArgs = {"executor"}; - SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), null, false); - } - // check for callAbort permission SecurityManager secMgr = System.getSecurityManager(); if (secMgr != null) { @@ -3186,11 +3185,20 @@ public void abort(Executor executor) throws SQLException { SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, true); } } + if (null == executor) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidArgument")); + Object[] msgArgs = {"executor"}; + SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), null, false); + } else { - setState(State.Closed); + /* + * Always report the connection as closed for any further use, no matter what happens when we try to clean + * up the physical resources associated with the connection using executor. + */ + setState(State.Closed); - if (null != tdsChannel && null != executor) - executor.execute(() -> tdsChannel.close()); + executor.execute(() -> clearConnectionResources()); + } loggerExternal.exiting(getClassNameLogging(), "abort"); } @@ -3199,19 +3207,27 @@ public void abort(Executor executor) throws SQLException { public void close() throws SQLServerException { loggerExternal.entering(getClassNameLogging(), "close"); - // Always report the connection as closed for any further use, no matter - // what happens when we try to clean up the physical resources associated - // with the connection. + /* + * Always report the connection as closed for any further use, no matter what happens when we try to clean up + * the physical resources associated with the connection. + */ setState(State.Closed); + clearConnectionResources(); + + loggerExternal.exiting(getClassNameLogging(), "close"); + } + + private void clearConnectionResources() { if (sharedTimer != null) { sharedTimer.removeRef(); sharedTimer = null; } - // Close the TDS channel. When the channel is closed, the server automatically - // rolls back any pending transactions and closes associated resources like - // prepared handles. + /* + * Close the TDS channel. When the channel is closed, the server automatically rolls back any pending + * transactions and closes associated resources like prepared handles. + */ if (null != tdsChannel) { tdsChannel.close(); } @@ -3227,8 +3243,6 @@ public void close() throws SQLServerException { cleanupPreparedStatementDiscardActions(); ActivityCorrelator.cleanupActivityId(); - - loggerExternal.exiting(getClassNameLogging(), "close"); } // This function is used by the proxy for notifying the pool manager that this connection proxy is closed @@ -6227,35 +6241,57 @@ public void onEviction(CityHash128Key key, PreparedStatementHandle handle) { } } } - - boolean isAzureDW() throws SQLServerException, SQLException { - if (null == isAzureDW) { - try (Statement stmt = this.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT CAST(SERVERPROPERTY('EngineEdition') as INT)")) { - // SERVERPROPERTY('EngineEdition') can be used to determine whether the db server is SQL Azure. - // It should return 6 for SQL Azure DW. This is more reliable than @@version or - // serverproperty('edition'). - // Reference: http://msdn.microsoft.com/en-us/library/ee336261.aspx - // - // SERVERPROPERTY('EngineEdition') means - // Database Engine edition of the instance of SQL Server installed on the server. - // 1 = Personal or Desktop Engine (Not available for SQL Server.) - // 2 = Standard (This is returned for Standard and Workgroup.) - // 3 = Enterprise (This is returned for Enterprise, Enterprise Evaluation, and Developer.) - // 4 = Express (This is returned for Express, Express with Advanced Services, and Windows Embedded SQL.) - // 5 = SQL Azure - // 6 = SQL Azure DW - // Base data type: int - final int ENGINE_EDITION_FOR_SQL_AZURE_DW = 6; + + /* + * SERVERPROPERTY('EngineEdition') can be used to determine whether the db server is SQL Azure. + * It should return 6 for SQL Azure DW. This is more reliable than @@version or + * serverproperty('edition'). + * Reference: http://msdn.microsoft.com/en-us/library/ee336261.aspx + * + * SERVERPROPERTY('EngineEdition') means + * Database Engine edition of the instance of SQL Server installed on the server. + * 1 = Personal or Desktop Engine (Not available for SQL Server.) + * 2 = Standard (This is returned for Standard and Workgroup.) + * 3 = Enterprise (This is returned for Enterprise, Enterprise Evaluation, and Developer.) + * 4 = Express (This is returned for Express, Express with Advanced Services, and Windows Embedded SQL.) + * 5 = SQL Azure + * 6 = SQL Azure DW + * 8 = Managed Instance + * Base data type: int + */ + boolean isAzure() { + if (null == isAzure) { + try (Statement stmt = this.createStatement(); ResultSet rs = stmt.executeQuery("SELECT CAST(SERVERPROPERTY('EngineEdition') as INT)")) { rs.next(); - isAzureDW = rs.getInt(1) == ENGINE_EDITION_FOR_SQL_AZURE_DW; + + int engineEdition = rs.getInt(1); + isAzure = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE || engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_DW || engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_MI); + isAzureDW = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_DW); + isAzureMI = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_MI); + + } catch (SQLException e) { + if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) + loggerExternal.log(Level.FINER, this + ": Error retrieving server type", e); + isAzure = false; + isAzureDW = false; + isAzureMI = false; } - return isAzureDW; + return isAzure; } else { - return isAzureDW; + return isAzure; } } + boolean isAzureDW() { + isAzure(); + return isAzureDW; + } + + boolean isAzureMI() { + isAzure(); + return isAzureMI; + } + /** * Adds statement to openStatements * diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java index 760f3f082..4f3edc2e9 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java @@ -8,7 +8,6 @@ import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; import java.text.MessageFormat; import java.util.Enumeration; import java.util.Locale; @@ -126,6 +125,7 @@ private SSLProtocol(String name) { this.name = name; } + @Override public String toString() { return name; } @@ -207,6 +207,7 @@ private ApplicationIntent(String value) { /** * Returns the string value of enum. */ + @Override public String toString() { return value; } @@ -250,6 +251,7 @@ public String getDefaultValue() { return defaultValue; } + @Override public String toString() { return name; } @@ -298,6 +300,7 @@ String getDefaultValue() { return defaultValue; } + @Override public String toString() { return name; } @@ -327,6 +330,7 @@ int getDefaultValue() { return defaultValue; } + @Override public String toString() { return name; } @@ -361,6 +365,7 @@ boolean getDefaultValue() { return defaultValue; } + @Override public String toString() { return name; } @@ -539,6 +544,7 @@ private static int nextInstanceID() { return baseID.incrementAndGet(); } + @Override final public String toString() { return traceID; } @@ -720,6 +726,7 @@ static String getPropertyOnlyName(String name, Logger logger) { return null; } + @Override public java.sql.Connection connect(String Url, Properties suppliedProperties) throws SQLServerException { loggerExternal.entering(getClassNameLogging(), "connect", "Arguments not traced."); SQLServerConnection result = null; @@ -759,6 +766,7 @@ private Properties parseAndMergeProperties(String Url, Properties suppliedProper return connectProperties; } + @Override public boolean acceptsURL(String url) throws SQLServerException { loggerExternal.entering(getClassNameLogging(), "acceptsURL", "Arguments not traced."); @@ -777,6 +785,7 @@ public boolean acceptsURL(String url) throws SQLServerException { return result; } + @Override public DriverPropertyInfo[] getPropertyInfo(String Url, Properties Info) throws SQLServerException { loggerExternal.entering(getClassNameLogging(), "getPropertyInfo", "Arguments not traced."); @@ -798,22 +807,26 @@ static final DriverPropertyInfo[] getPropertyInfoFromProperties(Properties props return properties; } + @Override public int getMajorVersion() { loggerExternal.entering(getClassNameLogging(), "getMajorVersion"); loggerExternal.exiting(getClassNameLogging(), "getMajorVersion", SQLJdbcVersion.major); return SQLJdbcVersion.major; } + @Override public int getMinorVersion() { loggerExternal.entering(getClassNameLogging(), "getMinorVersion"); loggerExternal.exiting(getClassNameLogging(), "getMinorVersion", SQLJdbcVersion.minor); return SQLJdbcVersion.minor; } - public Logger getParentLogger() throws SQLFeatureNotSupportedException { + @Override + public Logger getParentLogger() { return parentLogger; } + @Override public boolean jdbcCompliant() { loggerExternal.entering(getClassNameLogging(), "jdbcCompliant"); loggerExternal.exiting(getClassNameLogging(), "jdbcCompliant", Boolean.TRUE); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerLob.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerLob.java index 41eb1b5c6..52603994d 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerLob.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerLob.java @@ -8,7 +8,7 @@ import java.sql.SQLException; -abstract class SQLServerLob implements Serializable{ +abstract class SQLServerLob implements Serializable { /** * Always update serialVersionUID when prompted. diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMetaData.java index dfb43f756..aef7aac02 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerMetaData.java @@ -61,8 +61,8 @@ public SQLServerMetaData(String columnName, int sqlType, int precision, int scal } /** - * Constructs a SQLServerMetaData with the column name, SQL type, and length (for String data). - * The length is used to differentiate large strings from strings with length less than 4000 characters. + * Constructs a SQLServerMetaData with the column name, SQL type, and length (for String data). The length is used + * to differentiate large strings from strings with length less than 4000 characters. * * @param columnName * the name of the column diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java index 4d95cda9a..1efbd8572 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java @@ -254,7 +254,7 @@ private void parseQueryMeta(ResultSet rsQueryMeta) throws SQLServerException { SQLServerException.getErrString("R_metaDataErrorForParameter")); Object[] msgArgs = {paramOrdinal}; SQLServerException.makeFromDriverError(con, stmtParent, - form.format(msgArgs) + " " + e.toString(), null, false); + form.format(msgArgs) + " " + e.getMessage(), null, false); } } } else @@ -547,8 +547,8 @@ private void checkClosed() throws SQLServerException { * the procedure name * @throws SQLServerException */ + @SuppressWarnings("serial") SQLServerParameterMetaData(SQLServerPreparedStatement st, String sProcString) throws SQLServerException { - assert null != st; stmtParent = st; con = st.connection; @@ -612,9 +612,8 @@ private void checkClosed() throws SQLServerException { if (con.getServerMajorVersion() >= SQL_SERVER_2012_VERSION) { // new implementation for SQL verser 2012 and above - String preparedSQL = con.replaceParameterMarkers((stmtParent).userSQL, - (stmtParent).userSQLParamPositions, (stmtParent).inOutParam, - (stmtParent).bReturnValueSyntax); + String preparedSQL = con.replaceParameterMarkers(stmtParent.userSQL, + stmtParent.userSQLParamPositions, stmtParent.inOutParam, stmtParent.bReturnValueSyntax); try (SQLServerCallableStatement cstmt = (SQLServerCallableStatement) con .prepareCall("exec sp_describe_undeclared_parameters ?")) { @@ -680,9 +679,9 @@ private void checkClosed() throws SQLServerException { catch (SQLServerException e) { throw e; } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); + SQLServerException.makeFromDriverError(con, stmtParent, e.getMessage(), null, false); } catch (StringIndexOutOfBoundsException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); + SQLServerException.makeFromDriverError(con, stmtParent, e.getMessage(), null, false); } } @@ -703,49 +702,58 @@ public T unwrap(Class iface) throws SQLException { return t; } - private Map getParameterInfo(int param) throws SQLServerException { - boolean paramFound = false; - if ((stmtParent).bReturnValueSyntax && isTVP) { - paramFound = procMetadata.size() >= param; - if (paramFound) { - return procMetadata.get(param - 1); - } + private Map getParameterInfo(int param) { + if (stmtParent.bReturnValueSyntax && isTVP) { + return procMetadata.get(param - 1); } else { // Note row 1 is the 'return value' meta data - paramFound = procMetadata.size() > param; - if (paramFound) { - return procMetadata.get(param); - } + return procMetadata.get(param); } - if (!paramFound) { + } + + private boolean isValidParamProc(int n) { + // Note row 1 is the 'return value' meta data + return ((stmtParent.bReturnValueSyntax && isTVP && procMetadata.size() >= n) || procMetadata.size() > n); + } + + private boolean isValidParamQuery(int n) { + return (null != queryMetaMap && queryMetaMap.containsKey(n)); + } + + /** + * Checks if the @param passed is valid for either procedure metadata or query metadata. + * + * @param param + * @throws SQLServerException + */ + private void checkParam(int param) throws SQLServerException { + // Check if Procedure Metadata is not available + if (null == procMetadata) { + // Check if Query Metadata is also not available + if (!isValidParamQuery(param)) { + SQLServerException.makeFromDriverError(con, stmtParent, SQLServerException.getErrString("R_noMetadata"), + null, false); + } + } else if (!isValidParamProc(param)) { + // Throw exception if @param index not found MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidParameterNumber")); Object[] msgArgs = {param}; SQLServerException.makeFromDriverError(con, stmtParent, form.format(msgArgs), null, false); } - return null; - } - - private void checkParam(int n) throws SQLServerException { - if (!queryMetaMap.containsKey(n)) { - SQLServerException.makeFromDriverError(con, stmtParent, SQLServerException.getErrString("R_noMetadata"), - null, false); - } } @Override public String getParameterClassName(int param) throws SQLServerException { checkClosed(); + checkParam(param); try { - if (procMetadata == null) { - // PreparedStatement. - checkParam(param); + if (null == procMetadata) { return queryMetaMap.get(param).parameterClassName; } else { - JDBCType jdbcType = JDBCType.of((short) getParameterInfo(param).get("DATA_TYPE")); - return jdbcType.className(); + return JDBCType.of((short) getParameterInfo(param).get("DATA_TYPE")).className(); } - } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); + } catch (SQLServerException e) { + SQLServerException.makeFromDriverError(con, stmtParent, e.getMessage(), null, false); return null; } } @@ -753,8 +761,7 @@ public String getParameterClassName(int param) throws SQLServerException { @Override public int getParameterCount() throws SQLServerException { checkClosed(); - if (procMetadata == null) { - // PreparedStatement + if (null == procMetadata) { return queryMetaMap.size(); } else { // Row 1 is Return Type metadata @@ -765,139 +772,92 @@ public int getParameterCount() throws SQLServerException { @Override public int getParameterMode(int param) throws SQLServerException { checkClosed(); - try { - if (procMetadata == null) { - checkParam(param); - // if it is not a stored proc, the param can only be input. + checkParam(param); + if (null == procMetadata) { + // if it is not a stored procedure, the @param can only be input. + return parameterModeIn; + } else { + int n = (int) getParameterInfo(param).get("COLUMN_TYPE"); + if (n == 1) return parameterModeIn; - } else { - int n = (int) getParameterInfo(param).get("COLUMN_TYPE"); - switch (n) { - case 1: - return parameterModeIn; - case 2: - return parameterModeOut; - default: - return parameterModeUnknown; - } - } - } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return parameterModeUnknown; + else if (n == 2) + return parameterModeOut; + else + return parameterModeUnknown; } } @Override public int getParameterType(int param) throws SQLServerException { checkClosed(); + checkParam(param); int parameterType = 0; - try { - if (procMetadata == null) { - // PreparedStatement. - checkParam(param); - parameterType = queryMetaMap.get(param).parameterType; - } else { - Map info = getParameterInfo(param); - if (null != info) { - parameterType = (short) info.get("DATA_TYPE"); - } - } - if (0 != parameterType) { - switch (parameterType) { - case microsoft.sql.Types.DATETIME: - case microsoft.sql.Types.SMALLDATETIME: - parameterType = SSType.DATETIME2.getJDBCType().asJavaSqlType(); - break; - case microsoft.sql.Types.MONEY: - case microsoft.sql.Types.SMALLMONEY: - parameterType = SSType.DECIMAL.getJDBCType().asJavaSqlType(); - break; - case microsoft.sql.Types.GUID: - parameterType = SSType.CHAR.getJDBCType().asJavaSqlType(); - break; - default: - break; - } + if (null == procMetadata) { + parameterType = queryMetaMap.get(param).parameterType; + } else { + parameterType = (short) getParameterInfo(param).get("DATA_TYPE"); + } + if (0 != parameterType) { + switch (parameterType) { + case microsoft.sql.Types.DATETIME: + case microsoft.sql.Types.SMALLDATETIME: + parameterType = SSType.DATETIME2.getJDBCType().asJavaSqlType(); + break; + case microsoft.sql.Types.MONEY: + case microsoft.sql.Types.SMALLMONEY: + parameterType = SSType.DECIMAL.getJDBCType().asJavaSqlType(); + break; + case microsoft.sql.Types.GUID: + parameterType = SSType.CHAR.getJDBCType().asJavaSqlType(); + break; + default: + break; } - return parameterType; - } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; } + return parameterType; } @Override public String getParameterTypeName(int param) throws SQLServerException { checkClosed(); - try { - if (procMetadata == null) { - // PreparedStatement. - checkParam(param); - return queryMetaMap.get(param).parameterTypeName; - } else { - return getParameterInfo(param).get("TYPE_NAME").toString(); - } - } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return null; + checkParam(param); + if (null == procMetadata) { + return queryMetaMap.get(param).parameterTypeName; + } else { + return getParameterInfo(param).get("TYPE_NAME").toString(); } } @Override public int getPrecision(int param) throws SQLServerException { checkClosed(); - try { - if (procMetadata == null) { - // PreparedStatement. - checkParam(param); - return queryMetaMap.get(param).precision; - } else { - int nPrec = (int) getParameterInfo(param).get("PRECISION"); - return nPrec; - } - } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + checkParam(param); + if (null == procMetadata) { + return queryMetaMap.get(param).precision; + } else { + return (int) getParameterInfo(param).get("PRECISION"); } } @Override public int getScale(int param) throws SQLServerException { checkClosed(); - try { - if (procMetadata == null) { - // PreparedStatement. - checkParam(param); - return queryMetaMap.get(param).scale; - } else { - int nScale = (int) getParameterInfo(param).get("SCALE"); - return nScale; - } - } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + checkParam(param); + if (null == procMetadata) { + return queryMetaMap.get(param).scale; + } else { + return (int) getParameterInfo(param).get("SCALE"); } } @Override public int isNullable(int param) throws SQLServerException { checkClosed(); - try { - if (procMetadata == null) { - // PreparedStatement. - checkParam(param); - return queryMetaMap.get(param).isNullable; - } else { - int nNull = (int) getParameterInfo(param).get("NULLABLE"); - if (nNull == 1) - return parameterNullable; - if (nNull == 0) - return parameterNoNulls; - return parameterNullableUnknown; - } - } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return parameterNoNulls; + checkParam(param); + if (procMetadata == null) { + return queryMetaMap.get(param).isNullable; + } else { + return (int) getParameterInfo(param).get("NULLABLE"); } } @@ -905,7 +865,7 @@ public int isNullable(int param) throws SQLServerException { * Returns if a supplied parameter index is valid. * * @param param - * the param index + * the @param index * @throws SQLServerException * when an error occurs * @return boolean @@ -913,22 +873,22 @@ public int isNullable(int param) throws SQLServerException { @Override public boolean isSigned(int param) throws SQLServerException { checkClosed(); + checkParam(param); try { - if (procMetadata == null) { - // PreparedStatement. - checkParam(param); + if (null == procMetadata) { return queryMetaMap.get(param).isSigned; } else { return JDBCType.of((short) getParameterInfo(param).get("DATA_TYPE")).isSigned(); } } catch (SQLException e) { - SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); + SQLServerException.makeFromDriverError(con, stmtParent, e.getMessage(), null, false); return false; } } String getTVPSchemaFromStoredProcedure(int param) throws SQLServerException { checkClosed(); + checkParam(param); return (String) getParameterInfo(param).get("SS_TYPE_SCHEMA_NAME"); } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSetMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSetMetaData.java index d9e412515..aba77f885 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSetMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSetMetaData.java @@ -21,7 +21,7 @@ public final class SQLServerResultSetMetaData implements ISQLServerResultSetMeta * Always update serialVersionUID when prompted. */ private static final long serialVersionUID = -5747558730471411712L; - + private SQLServerConnection con; private final SQLServerResultSet rs; static final private java.util.logging.Logger logger = java.util.logging.Logger diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSavepoint.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSavepoint.java index fa6552d86..09c38dd74 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSavepoint.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerSavepoint.java @@ -21,7 +21,7 @@ public final class SQLServerSavepoint implements ISQLServerSavepoint { * Always update serialVersionUID when prompted. */ private static final long serialVersionUID = 1857415943191289598L; - + private final String sName; private final int nId; private final SQLServerConnection con; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java index 3db1126d2..262240bfd 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java @@ -54,7 +54,7 @@ public class SQLServerStatement implements ISQLServerStatement { * Always update serialVersionUID when prompted. */ private static final long serialVersionUID = -4421134713913331507L; - + final static char LEFT_CURLY_BRACKET = 123; final static char RIGHT_CURLY_BRACKET = 125; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java index 82f4a3813..1fa481f8f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java @@ -738,11 +738,16 @@ private void sendTemporal(DTV dtv, JavaType javaType, Object value) throws SQLSe if (null != typeInfo) // updater { switch (typeInfo.getSSType()) { + case DATETIME: case DATETIME2: - // Default and max fractional precision is 7 digits (100ns) + /* Default and max fractional precision is 7 digits (100ns) + * Send DateTime2 to DateTime columns to let the server handle nanosecond rounding. Also + * adjust scale accordingly to avoid rounding on driver's end. + */ + int scale = (typeInfo.getSSType() == SSType.DATETIME) ? typeInfo.getScale() + 4 : typeInfo.getScale(); tdsWriter.writeRPCDateTime2(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()), subSecondNanos, - typeInfo.getScale(), isOutParam); + scale, isOutParam); break; @@ -773,7 +778,6 @@ private void sendTemporal(DTV dtv, JavaType javaType, Object value) throws SQLSe break; - case DATETIME: case SMALLDATETIME: tdsWriter.writeRPCDateTime(name, timestampNormalizedCalendar(calendar, javaType, conn.baseYear()), subSecondNanos, diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java b/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java index 4e07bc6b5..3cd436107 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/tdsparser.java @@ -255,8 +255,8 @@ boolean onTabName(TDSReader tdsReader) throws SQLServerException { void onEOF(TDSReader tdsReader) throws SQLServerException { if (null != getDatabaseError()) { - SQLServerException.makeFromDatabaseError(tdsReader.getConnection(), null, getDatabaseError().getErrorMessage(), - getDatabaseError(), false); + SQLServerException.makeFromDatabaseError(tdsReader.getConnection(), null, + getDatabaseError().getErrorMessage(), getDatabaseError(), false); } } diff --git a/src/main/java/mssql/googlecode/concurrentlinkedhashmap/Linked.java b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/Linked.java new file mode 100644 index 000000000..21fbc533f --- /dev/null +++ b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/Linked.java @@ -0,0 +1,27 @@ +package mssql.googlecode.concurrentlinkedhashmap; + +import java.util.Deque; + +/** + * An element that is linked on the {@link Deque}. + */ +interface Linked> { + + /** + * Retrieves the previous element or null if either the element is + * unlinked or the first element on the deque. + */ + T getPrevious(); + + /** Sets the previous element or null if there is no link. */ + void setPrevious(T prev); + + /** + * Retrieves the next element or null if either the element is + * unlinked or the last element on the deque. + */ + T getNext(); + + /** Sets the next element or null if there is no link. */ + void setNext(T next); +} diff --git a/src/main/java/mssql/googlecode/concurrentlinkedhashmap/LinkedDeque.java b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/LinkedDeque.java index 2bb23ea78..ffa048c9f 100644 --- a/src/main/java/mssql/googlecode/concurrentlinkedhashmap/LinkedDeque.java +++ b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/LinkedDeque.java @@ -434,27 +434,3 @@ public void remove() { abstract E computeNext(); } } - -/** - * An element that is linked on the {@link Deque}. - */ -interface Linked> { - - /** - * Retrieves the previous element or null if either the element is - * unlinked or the first element on the deque. - */ - T getPrevious(); - - /** Sets the previous element or null if there is no link. */ - void setPrevious(T prev); - - /** - * Retrieves the next element or null if either the element is - * unlinked or the last element on the deque. - */ - T getNext(); - - /** Sets the next element or null if there is no link. */ - void setNext(T next); -} 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 2a5fd18fc..e4ead7fd5 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -12,15 +12,15 @@ import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; +import java.sql.Connection; import java.sql.Date; -import java.sql.DriverManager; import java.sql.JDBCType; import java.sql.SQLException; +import java.sql.Statement; import java.sql.Time; 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; @@ -29,7 +29,6 @@ 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; @@ -40,7 +39,9 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.PrepUtil; import microsoft.sql.DateTimeOffset; @@ -54,26 +55,11 @@ @RunWith(JUnitPlatform.class) public class AESetup extends AbstractTest { - static final String javaKeyStoreInputFile = "JavaKeyStore.txt"; - static final String keyStoreName = "MSSQL_JAVA_KEYSTORE"; - static final String jksName = "clientcert.jks"; - static final String cmkName = "JDBC_CMK"; - static final String cekName = "JDBC_CEK"; - static final String secretstrJks = "password"; - - 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 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; @@ -93,24 +79,24 @@ public static void setUpConnection() throws TestAbortedException, Exception { } AETestConnectionString = connectionString + ";sendTimeAsDateTime=false"; - readFromFile(javaKeyStoreInputFile, "Alias name"); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString); + readFromFile(Constants.JAVA_KEY_STORE_FILENAME, "Alias name"); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropCEK(stmt); dropCMK(stmt); } - keyPath = TestUtils.getCurrentClassPath() + jksName; - storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, secretstrJks.toCharArray()); + keyPath = TestUtils.getCurrentClassPath() + Constants.JKS_NAME; + storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, Constants.JKS_SECRET.toCharArray()); stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.Enabled; AEInfo = new Properties(); - AEInfo.setProperty("ColumnEncryptionSetting", "Enabled"); - AEInfo.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); + AEInfo.setProperty("ColumnEncryptionSetting", Constants.ENABLED); + AEInfo.setProperty("keyStoreAuthentication", Constants.JAVA_KEY_STORE_PASSWORD); AEInfo.setProperty("keyStoreLocation", keyPath); - AEInfo.setProperty("keyStoreSecret", secretstrJks); + AEInfo.setProperty("keyStoreSecret", Constants.JKS_SECRET); - createCMK(keyStoreName, javaKeyAliases); + createCMK(Constants.JAVA_KEY_STORE_NAME, javaKeyAliases); createCEK(storeProvider); } @@ -126,8 +112,7 @@ public static void dropAll() throws Exception { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { dropTables(stmt); dropCEK(stmt); dropCMK(stmt); @@ -160,7 +145,7 @@ private static void readFromFile(String inputFile, String lookupValue) throws IO } } } catch (IOException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -170,45 +155,45 @@ private static void readFromFile(String inputFile, String lookupValue) throws IO * @throws SQLException */ protected static void createBinaryTable() throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE) + " (" + "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," + + Constants.CEK_NAME + ") NULL," + "DeterministicBinary binary(20) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainVarbinary varbinary(50) null," + "RandomizedVarbinary varbinary(50) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicVarbinary varbinary(50) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainVarbinaryMax varbinary(max) null," + "RandomizedVarbinaryMax varbinary(max) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicVarbinaryMax varbinary(max) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainBinary512 binary(512) null," + "RandomizedBinary512 binary(512) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicBinary512 binary(512) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainBinary8000 varbinary(8000) null," + "RandomizedBinary8000 varbinary(8000) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicBinary8000 varbinary(8000) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -218,69 +203,69 @@ protected static void createBinaryTable() throws SQLException { * @throws SQLException */ protected static void createCharTable() throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " (" + "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," + + Constants.CEK_NAME + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainVarchar varchar(50) null," + "RandomizedVarchar varchar(50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "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," + + Constants.CEK_NAME + ") NULL," + "PlainVarcharMax varchar(max) null," + "RandomizedVarcharMax varchar(max) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicVarcharMax varchar(max) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNchar nchar(30) null," + "RandomizedNchar nchar(30) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNchar nchar(30) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNvarchar nvarchar(60) null," + "RandomizedNvarchar nvarchar(60) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNvarchar nvarchar(60) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNvarcharMax nvarchar(max) null," + "RandomizedNvarcharMax nvarchar(max) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNvarcharMax nvarchar(max) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainUniqueidentifier uniqueidentifier null," + "RandomizedUniqueidentifier uniqueidentifier ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicUniqueidentifier uniqueidentifier ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainVarchar8000 varchar(8000) null," + "RandomizedVarchar8000 varchar(8000) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicVarchar8000 varchar(8000) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNvarchar4000 nvarchar(4000) null," + "RandomizedNvarchar4000 nvarchar(4000) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNvarchar4000 nvarchar(4000) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -290,50 +275,51 @@ protected static void createCharTable() throws SQLException { * @throws SQLException */ protected void createDateTable() throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + "PlainDate date null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " (" + + "PlainDate date null," + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDate date ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetime2Default datetime2 null," + "RandomizedDatetime2Default datetime2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetime2Default datetime2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetimeoffsetDefault datetimeoffset null," + "RandomizedDatetimeoffsetDefault datetimeoffset ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetimeoffsetDefault datetimeoffset ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainTimeDefault time null," + "RandomizedTimeDefault time ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTimeDefault time ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetime datetime null," + "RandomizedDatetime datetime ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetime datetime ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainSmalldatetime smalldatetime null," + "RandomizedSmalldatetime smalldatetime ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicSmalldatetime smalldatetime ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -343,58 +329,58 @@ protected void createDateTable() throws SQLException { * @throws SQLException */ protected void createDatePrecisionTable(int scale) throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " (" // 1 + "PlainDatetime2 datetime2(" + scale + ") null," + "RandomizedDatetime2 datetime2(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "DeterministicDatetime2 datetime2(" + scale + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetime2 datetime2(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," // 4 + "PlainDatetime2Default datetime2 null," + "RandomizedDatetime2Default datetime2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetime2Default datetime2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," // 7 + "PlainDatetimeoffsetDefault datetimeoffset null," + "RandomizedDatetimeoffsetDefault datetimeoffset ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetimeoffsetDefault datetimeoffset ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," // 10 + "PlainTimeDefault time null," + "RandomizedTimeDefault time ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTimeDefault time ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," // 13 + "PlainTime time(" + scale + ") null," + "RandomizedTime time(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "DeterministicTime time(" + scale + + Constants.CEK_NAME + ") NULL," + "DeterministicTime time(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," // 16 + "PlainDatetimeoffset datetimeoffset(" + scale + ") null," + "RandomizedDatetimeoffset datetimeoffset(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "DeterministicDatetimeoffset datetimeoffset(" + scale + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetimeoffset datetimeoffset(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -404,34 +390,34 @@ protected void createDatePrecisionTable(int scale) throws SQLException { * @throws SQLException */ protected static void createDateScaleTable() throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.SCALE_DATE_TABLE_AE) + " (" + "PlainDatetime2 datetime2(2) null," + "RandomizedDatetime2 datetime2(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetime2 datetime2(2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainTime time(2) null," + "RandomizedTime time(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTime time(2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetimeoffset datetimeoffset(2) null," + "RandomizedDatetimeoffset datetimeoffset(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetimeoffset datetimeoffset(2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -441,110 +427,111 @@ protected static void createDateScaleTable() throws SQLException { * @throws SQLException */ protected static void createNumericTable() throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainBit bit null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " (" + + "PlainBit bit null," + "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainTinyint tinyint null," + "RandomizedTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainSmallint smallint null," + "RandomizedSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainInt int null," + "RandomizedInt int ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicInt int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainBigint bigint null," + "RandomizedBigint bigint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicBigint bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainFloatDefault float null," + "RandomizedFloatDefault float ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicFloatDefault float ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainFloat float(30) null," + "RandomizedFloat float(30) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicFloat float(30) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainReal real null," + "RandomizedReal real ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicReal real ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDecimalDefault decimal null," + "RandomizedDecimalDefault decimal ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDecimalDefault decimal ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDecimal decimal(10,5) null," + "RandomizedDecimal decimal(10,5) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDecimal decimal(10,5) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNumericDefault numeric null," + "RandomizedNumericDefault numeric ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNumericDefault numeric ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNumeric numeric(8,2) null," + "RandomizedNumeric numeric(8,2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNumeric numeric(8,2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainSmallMoney smallmoney null," + "RandomizedSmallMoney smallmoney ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicSmallMoney smallmoney ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainMoney money null," + "RandomizedMoney money ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicMoney money ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDecimal2 decimal(28,4) null," + "RandomizedDecimal2 decimal(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDecimal2 decimal(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNumeric2 numeric(28,4) null," + "RandomizedNumeric2 numeric(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNumeric2 numeric(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -554,35 +541,35 @@ protected static void createNumericTable() throws SQLException { * @throws SQLException */ protected void createNumericPrecisionTable(int floatPrecision, int precision, int scale) throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainFloat float(" - + floatPrecision + ") null," + "RandomizedFloat float(" + floatPrecision + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " (" + + "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 + + Constants.CEK_NAME + ") NULL," + "DeterministicFloat float(" + floatPrecision + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDecimal decimal(" + precision + "," + scale + ") null," + "RandomizedDecimal decimal(" + precision + "," + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "DeterministicDecimal decimal(" + precision + "," + scale + + Constants.CEK_NAME + ") NULL," + "DeterministicDecimal decimal(" + precision + "," + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNumeric numeric(" + precision + "," + scale + ") null," + "RandomizedNumeric numeric(" + precision + "," + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "DeterministicNumeric numeric(" + precision + "," + scale + + Constants.CEK_NAME + ") NULL," + "DeterministicNumeric numeric(" + precision + "," + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL" + + Constants.CEK_NAME + ") NULL" + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -629,8 +616,8 @@ protected static String[] createCharValues(boolean nullable) { String varchar8000 = RandomData.generateCharTypes("8000", nullable, encrypted); String nvarchar4000 = RandomData.generateNCharTypes("4000", nullable, encrypted); - String[] values = {char20.trim(), varchar50, varcharmax, nchar30, nvarchar60, nvarcharmax, uid, varchar8000, - nvarchar4000}; + String[] values = {char20.trim(), varchar50, varcharmax, nchar30, nvarchar60, nvarcharmax, Constants.UID, + varchar8000, nvarchar4000}; return values; } @@ -700,12 +687,12 @@ protected static LinkedList createTemporalTypes(boolean nullable) { * @throws SQLException */ private static void createCMK(String keyStoreName, String keyPath) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager + try (SQLServerConnection con = (SQLServerConnection) PrepUtil .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 = '" - + keyStoreName + "', KEY_PATH = '" + keyPath + "')" + " end"; + String sql = " if not exists (SELECT name from sys.column_master_keys where name='" + Constants.CMK_NAME + + "')" + " begin" + " CREATE COLUMN MASTER KEY " + Constants.CMK_NAME + + " WITH (KEY_STORE_PROVIDER_NAME = '" + keyStoreName + "', KEY_PATH = '" + keyPath + "')" + " end"; stmt.execute(sql); } } @@ -718,16 +705,16 @@ private static void createCMK(String keyStoreName, String keyPath) throws SQLExc * @throws SQLException */ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storeProvider) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager + try (SQLServerConnection con = (SQLServerConnection) PrepUtil .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { - String letters = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - byte[] valuesDefault = letters.getBytes(); + byte[] valuesDefault = Constants.CEK_STRING.getBytes(); String cekSql = null; - byte[] key = storeProvider.encryptColumnEncryptionKey(javaKeyAliases, "RSA_OAEP", valuesDefault); - cekSql = "CREATE COLUMN ENCRYPTION KEY " + cekName + " WITH VALUES " + "(COLUMN_MASTER_KEY = " + cmkName - + ", ALGORITHM = 'RSA_OAEP', ENCRYPTED_VALUE = 0x" + TestUtils.bytesToHexString(key, key.length) - + ")" + ";"; + byte[] key = storeProvider.encryptColumnEncryptionKey(javaKeyAliases, Constants.CEK_ALGORITHM, + valuesDefault); + cekSql = "CREATE COLUMN ENCRYPTION KEY " + Constants.CEK_NAME + " WITH VALUES " + "(COLUMN_MASTER_KEY = " + + Constants.CMK_NAME + ", ALGORITHM = '" + Constants.CEK_ALGORITHM + "', ENCRYPTED_VALUE = 0x" + + TestUtils.bytesToHexString(key, key.length) + ");"; stmt.execute(cekSql); } } @@ -737,11 +724,11 @@ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storePro * * @throws SQLException */ - protected static void dropTables(SQLServerStatement statement) throws SQLException { - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), statement); - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), statement); - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(binaryTable), statement); - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateTable), statement); + protected static void dropTables(Statement stmt) throws SQLException { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE), stmt); } /** @@ -751,10 +738,10 @@ protected static void dropTables(SQLServerStatement statement) throws SQLExcepti * @throws SQLException */ protected static void populateBinaryNormalCase(LinkedList byteValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager + try (SQLServerConnection con = (SQLServerConnection) PrepUtil .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -815,10 +802,9 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th * @throws SQLException */ protected static void populateBinarySetObject(LinkedList byteValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -878,11 +864,10 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr * @throws SQLException */ protected static void populateBinarySetObjectWithJDBCType(LinkedList byteValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -941,11 +926,10 @@ protected static void populateBinarySetObjectWithJDBCType(LinkedList byt * @throws SQLException */ protected static void populateBinaryNullCase() throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -980,11 +964,10 @@ protected static void populateBinaryNullCase() throws SQLException { * @throws SQLException */ protected static void populateCharNormalCase(String[] charValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1023,7 +1006,7 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce if (null == charValues[6]) { pstmt.setUniqueIdentifier(i, null); } else { - pstmt.setUniqueIdentifier(i, uid); + pstmt.setUniqueIdentifier(i, Constants.UID); } } @@ -1048,11 +1031,10 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce * @throws SQLException */ protected static void populateCharSetObject(String[] charValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1112,11 +1094,10 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep * @throws SQLException */ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1175,11 +1156,10 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th * @throws SQLException */ protected static void populateCharNullCase() throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1230,11 +1210,10 @@ protected static void populateCharNullCase() throws SQLException { * @throws SQLException */ protected static void populateDateNormalCase(LinkedList dateValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1279,11 +1258,10 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro * @throws SQLException */ protected static void populateDateScaleNormalCase(LinkedList dateValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.SCALE_DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1315,11 +1293,10 @@ protected static void populateDateScaleNormalCase(LinkedList dateValues) */ protected static void populateDateSetObject(LinkedList dateValues, String setter) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1383,11 +1360,10 @@ else if (setter.equalsIgnoreCase("setwithJDBCType")) * @throws SQLException */ protected void populateDateSetObjectNull() throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1431,11 +1407,10 @@ protected void populateDateSetObjectNull() throws SQLException { * @throws SQLException */ protected static void populateDateNullCase() throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1480,18 +1455,17 @@ protected static void populateDateNullCase() throws SQLException { * @throws SQLException */ protected static void populateNumeric(String[] values) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { + if (values[0].equalsIgnoreCase(Boolean.TRUE.toString())) { pstmt.setBoolean(i, true); } else { pstmt.setBoolean(i, false); @@ -1590,18 +1564,17 @@ protected static void populateNumeric(String[] values) throws SQLException { * @throws SQLException */ protected static void populateNumericSetObject(String[] values) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { + if (values[0].equalsIgnoreCase(Boolean.TRUE.toString())) { pstmt.setObject(i, true); } else { pstmt.setObject(i, false); @@ -1700,18 +1673,17 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept * @throws SQLException */ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { + if (values[0].equalsIgnoreCase(Boolean.TRUE.toString())) { pstmt.setObject(i, true); } else { pstmt.setObject(i, false); @@ -1809,12 +1781,11 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr * @throws SQLException */ protected static void populateNumericSetObjectNull() throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -1909,14 +1880,13 @@ protected static void populateNumericSetObjectNull() throws SQLException { * @throws SQLException */ protected static void populateNumericNullCase(String[] values) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -2010,20 +1980,19 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti * @throws SQLException */ protected static void populateNumericNormalCase(String[] numericValues) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { + if (numericValues[0].equalsIgnoreCase(Boolean.TRUE.toString())) { pstmt.setBoolean(i, true); } else { pstmt.setBoolean(i, false); @@ -2122,9 +2091,9 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S * * @throws SQLException */ - 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"; + private static void dropCEK(Statement stmt) throws SQLException { + String cekSql = " if exists (SELECT name from sys.column_encryption_keys where name='" + Constants.CEK_NAME + + "')" + " begin" + " drop column encryption key " + Constants.CEK_NAME + " end"; stmt.execute(cekSql); } @@ -2133,9 +2102,9 @@ private static void dropCEK(SQLServerStatement stmt) throws SQLException { * * @throws SQLException */ - private static void dropCMK(SQLServerStatement stmt) throws SQLException { - String cekSql = " if exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')" + " begin" - + " drop column master key " + cmkName + " end"; + private static void dropCMK(Statement stmt) throws SQLException { + String cekSql = " if exists (SELECT name from sys.column_master_keys where name='" + Constants.CMK_NAME + "')" + + " begin" + " drop column master key " + Constants.CMK_NAME + " end"; stmt.execute(cekSql); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java index 33d41a931..e39c228b7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -11,7 +11,6 @@ import java.math.BigDecimal; import java.sql.Date; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; @@ -34,7 +33,9 @@ import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.PrepUtil; import microsoft.sql.DateTimeOffset; @@ -281,8 +282,8 @@ public void testOutputProcedure4() throws SQLException { } private static void dropProcedures() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.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); @@ -306,223 +307,222 @@ private static void dropProcedures() throws SQLException { } private static void dropTables() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.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(Constants.CHAR_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table5), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table6), stmt); - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(scaleDateTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.SCALE_DATE_TABLE_AE), stmt); } } private static void createTables() throws SQLException { 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," + + Constants.CEK_NAME + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainVarchar varchar(50) null," + "RandomizedVarchar varchar(50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "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" + ");"; + + Constants.CEK_NAME + ") NULL" + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } 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," + + Constants.CEK_NAME + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainVarchar varchar(50) null," + "RandomizedVarchar varchar(50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "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" + + Constants.CEK_NAME + ") NULL" + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } 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," + + Constants.CEK_NAME + ") NULL," + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainTinyint tinyint null," + "RandomizedTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainSmallint smallint null," + "RandomizedSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainInt int null," + "RandomizedInt int ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicInt int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainBigint bigint null," + "RandomizedBigint bigint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicBigint bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainFloatDefault float null," + "RandomizedFloatDefault float ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicFloatDefault float ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainFloat float(30) null," + "RandomizedFloat float(30) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicFloat float(30) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainReal real null," + "RandomizedReal real ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicReal real ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDecimalDefault decimal(18,0) null," + "RandomizedDecimalDefault decimal(18,0) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDecimalDefault decimal(18,0) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDecimal decimal(10,5) null," + "RandomizedDecimal decimal(10,5) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDecimal decimal(10,5) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNumericDefault numeric(18,0) null," + "RandomizedNumericDefault numeric(18,0) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNumericDefault numeric(18,0) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNumeric numeric(8,2) null," + "RandomizedNumeric numeric(8,2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNumeric numeric(8,2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainInt2 int null," + "RandomizedInt2 int ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicInt2 int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainSmallMoney smallmoney null," + "RandomizedSmallMoney smallmoney ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicSmallMoney smallmoney ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainMoney money null," + "RandomizedMoney money ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicMoney money ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDecimal2 decimal(28,4) null," + "RandomizedDecimal2 decimal(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDecimal2 decimal(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainNumeric2 numeric(28,4) null," + "RandomizedNumeric2 numeric(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicNumeric2 numeric(28,4) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } 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," + + Constants.CEK_NAME + ") NULL," + "DeterministicInt int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + ");"; + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } 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," + + Constants.CEK_NAME + ") NULL," + "c2 smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "c3 bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + ");"; + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } 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," + + Constants.CEK_NAME + ") NULL," + "c2 smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "c3 bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + ");"; + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } private static void populateTable4() throws SQLException { String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(table4) + " values( " + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -540,14 +540,13 @@ private static void populateTable3() throws SQLException { + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { + if (numericValues[0].equalsIgnoreCase(Boolean.TRUE.toString())) { pstmt.setBoolean(i, true); } else { pstmt.setBoolean(i, false); @@ -649,8 +648,8 @@ private void createMultiInsertionSelection() throws SQLException { + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure) @@ -668,8 +667,7 @@ private void createMultiInsertionSelection() throws SQLException { private void MultiInsertionSelection() throws SQLException { String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure) + " (?,?,?,?,?,?)}"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -700,7 +698,7 @@ private void MultiInsertionSelection() throws SQLException { results = callableStatement.getMoreResults(); } } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -723,8 +721,8 @@ private void createInputProcedure() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure) @@ -732,7 +730,7 @@ private void createInputProcedure() throws SQLException { + "@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) + + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " 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" @@ -745,8 +743,7 @@ private void createInputProcedure() throws SQLException { } private void testInputProcedure(String sql, String[] values) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -763,7 +760,7 @@ private void testInputProcedure(String sql, String[] values) throws SQLException callableStatement.setBigDecimal(5, new BigDecimal(values[10])); // numeric(18,0) callableStatement.setSmallMoney(6, new BigDecimal(values[12])); callableStatement.setMoney(7, new BigDecimal(values[13])); - if (values[0].equalsIgnoreCase("true")) + if (values[0].equalsIgnoreCase(Boolean.TRUE.toString())) callableStatement.setBoolean(8, true); else callableStatement.setBoolean(8, false); @@ -780,7 +777,7 @@ private void testInputProcedure(String sql, String[] values) throws SQLException assertEquals(rs.getString(1), values[3], "" + TestResource.getResource("R_inputParamFailed")); } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -789,8 +786,8 @@ private void createInputProcedure2() throws SQLException { + TestUtils.escapeSingleQuotes(inputProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2) @@ -798,7 +795,7 @@ private void createInputProcedure2() throws SQLException { + " @p6 varchar(8000), @p7 nvarchar(4000)" + " AS" + " SELECT top 1 RandomizedVarchar, DeterministicUniqueidentifier, DeterministicVarcharMax, RandomizedNchar, " + " DeterministicNvarchar, DeterministicNvarcharMax, DeterministicVarchar8000, RandomizedNvarchar4000 FROM " - + AbstractSQLGenerator.escapeIdentifier(charTable) + + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " where DeterministicVarchar = @p0 and DeterministicUniqueidentifier =@p1"; stmt.execute(sql); @@ -807,8 +804,7 @@ private void createInputProcedure2() throws SQLException { private void testInputProcedure2(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -834,7 +830,7 @@ private void testInputProcedure2(String sql) throws SQLException { assertEquals(rs.getString(8).trim(), charValues[8], TestResource.getResource("R_inputParamFailed")); } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -843,8 +839,8 @@ private void createOutputProcedure3() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) @@ -858,8 +854,7 @@ private void createOutputProcedure3() throws SQLException { private void testOutputProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -883,14 +878,13 @@ private void testOutputProcedure3RandomOrder(String sql) throws SQLException { int intValue5 = callableStatement.getInt(1); assertEquals("" + intValue5, numericValues[3], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedure3Inorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -905,14 +899,13 @@ private void testOutputProcedure3Inorder(String sql) throws SQLException { int intValue2 = callableStatement.getInt(2); assertEquals("" + intValue2, numericValues[3], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -927,7 +920,7 @@ private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { int intValue = callableStatement.getInt(1); assertEquals("" + intValue, numericValues[3], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -936,8 +929,8 @@ private void createOutputProcedure2() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) @@ -953,8 +946,7 @@ private void createOutputProcedure2() throws SQLException { private void testOutputProcedure2RandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1001,14 +993,13 @@ private void testOutputProcedure2RandomOrder(String sql, String[] values) throws int encryptedInt = callableStatement.getInt(2); assertEquals("" + encryptedInt, values[3], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedure2Inorder(String sql, String[] values) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1055,14 +1046,13 @@ private void testOutputProcedure2Inorder(String sql, String[] values) throws SQL assertEquals("" + encryptedMoney, values[13], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedure2ReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1092,6 +1082,7 @@ private void testOutputProcedure2ReverseOrder(String sql, String[] values) throw assertEquals("" + encryptedSmallMoney, values[12], TestResource.getResource("R_outputParamFailed")); short encryptedTinyint = callableStatement.getShort(6); + assertEquals("" + encryptedTinyint, values[1], TestResource.getResource("R_outputParamFailed")); short tinyintValue = callableStatement.getShort(5); assertEquals("" + tinyintValue, values[1], TestResource.getResource("R_outputParamFailed")); @@ -1109,7 +1100,7 @@ private void testOutputProcedure2ReverseOrder(String sql, String[] values) throw assertEquals("" + intValue, values[3], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1118,8 +1109,8 @@ private void createOutputProcedure() throws SQLException { + TestUtils.escapeSingleQuotes(outputProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) @@ -1135,8 +1126,7 @@ private void createOutputProcedure() throws SQLException { private void testOutputProcedureRandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1179,14 +1169,13 @@ private void testOutputProcedureRandomOrder(String sql, String[] values) throws BigDecimal money1 = callableStatement.getMoney(7); assertEquals("" + money1, "" + values[13], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedureInorder(String sql, String[] values) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1222,14 +1211,13 @@ private void testOutputProcedureInorder(String sql, String[] values) throws SQLE assertEquals("" + money1, values[13], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedureReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1264,7 +1252,7 @@ private void testOutputProcedureReverseOrder(String sql, String[] values) throws assertEquals("" + intValue2, values[3], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1273,8 +1261,8 @@ private void createInOutProcedure() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure) + " @p0 int OUTPUT" @@ -1287,8 +1275,7 @@ private void createInOutProcedure() throws SQLException { private void testInOutProcedure(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1300,7 +1287,7 @@ private void testInOutProcedure(String sql) throws SQLException { assertEquals("" + intValue, numericValues[3], "Test for Inout parameter fails.\n"); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1309,8 +1296,8 @@ private void createMixedProcedure() throws SQLException { + TestUtils.escapeSingleQuotes(mixedProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure) @@ -1325,8 +1312,7 @@ private void createMixedProcedure() throws SQLException { private void testMixedProcedure(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1349,7 +1335,7 @@ private void testMixedProcedure(String sql) throws SQLException { int returnedValue = callableStatement.getInt(1); assertEquals("" + returnedValue, "" + 123, "Test for Inout parameter fails.\n"); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1358,8 +1344,8 @@ private void createMixedProcedure2() throws SQLException { + TestUtils.escapeSingleQuotes(mixedProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2) @@ -1374,8 +1360,7 @@ private void createMixedProcedure2() throws SQLException { private void testMixedProcedure2RandomOrder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1404,14 +1389,13 @@ private void testMixedProcedure2RandomOrder(String sql) throws SQLException { assertEquals("" + floatValue3, numericValues[5], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testMixedProcedure2Inorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1427,7 +1411,7 @@ private void testMixedProcedure2Inorder(String sql) throws SQLException { double floatValue = callableStatement.getDouble(2); assertEquals("" + floatValue, numericValues[5], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1436,8 +1420,8 @@ private void createMixedProcedure3() throws SQLException { + TestUtils.escapeSingleQuotes(mixedProcedure3) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) @@ -1451,8 +1435,7 @@ private void createMixedProcedure3() throws SQLException { private void testMixedProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1481,14 +1464,13 @@ private void testMixedProcedure3RandomOrder(String sql) throws SQLException { assertEquals("" + bigintValue3, numericValues[4], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testMixedProcedure3Inorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1504,14 +1486,13 @@ private void testMixedProcedure3Inorder(String sql) throws SQLException { double floatValue = callableStatement.getDouble(2); assertEquals("" + floatValue, numericValues[5], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1527,7 +1508,7 @@ private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { long bigintValue = callableStatement.getLong(1); assertEquals("" + bigintValue, numericValues[4], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1537,8 +1518,8 @@ private void createMixedProcedureNumericPrcisionScale() throws SQLException { + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale) @@ -1554,8 +1535,7 @@ private void createMixedProcedureNumericPrcisionScale() throws SQLException { private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1580,14 +1560,13 @@ private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQ assertEquals(value4, new BigDecimal(numericValues[11]), "Test for input output parameter fails.\n"); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1612,7 +1591,7 @@ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) thr assertEquals(value4, new BigDecimal(numericValues[11]), "Test for input output parameter fails.\n"); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1621,8 +1600,8 @@ private void createOutputProcedureChar() throws SQLException { + TestUtils.escapeSingleQuotes(outputProcedureChar) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar) @@ -1631,7 +1610,7 @@ private void createOutputProcedureChar() throws SQLException { + " 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); + + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE); stmt.execute(sql); } @@ -1639,8 +1618,7 @@ private void createOutputProcedureChar() throws SQLException { private void testOutputProcedureCharInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1684,14 +1662,13 @@ private void testOutputProcedureCharInorder(String sql) throws SQLException { assertEquals(nvarcharValue4000, charValues[8], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedureCharInorderObject(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1738,7 +1715,7 @@ private void testOutputProcedureCharInorderObject(String sql) throws SQLExceptio assertEquals(nvarcharValue4000, charValues[8], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1748,8 +1725,8 @@ private void createOutputProcedureNumeric() throws SQLException { + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric) @@ -1761,7 +1738,7 @@ private void createOutputProcedureNumeric() throws SQLException { + " @p7=RandomizedReal, @p8=DeterministicDecimalDefault, @p9=RandomizedDecimal," + " @p10=DeterministicNumericDefault, @p11=RandomizedNumeric, @p12=RandomizedSmallMoney, @p13=DeterministicMoney," + " @p14=DeterministicDecimal2, @p15=DeterministicNumeric2 FROM " - + AbstractSQLGenerator.escapeIdentifier(numericTable); + + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE); stmt.execute(sql); } @@ -1769,8 +1746,7 @@ private void createOutputProcedureNumeric() throws SQLException { private void testOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1853,14 +1829,13 @@ private void testOutputProcedureNumericInorder(String sql) throws SQLException { TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -1883,7 +1858,7 @@ private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLE callableStatement.execute(); - Class[] boolean_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, + Class[] boolean_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigDecimal.class, String.class}; for (int i = 0; i < boolean_coercions.length; i++) { Object value = getxxx(1, boolean_coercions[i], callableStatement); @@ -1894,7 +1869,7 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() boolVal = false; assertEquals("" + boolVal, numericValues[0], TestResource.getResource("R_outputParamFailed")); } - Class[] tinyint_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, + Class[] tinyint_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigDecimal.class, String.class}; for (int i = 0; i < tinyint_coercions.length; i++) { @@ -1907,7 +1882,7 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() assertEquals(tinyIntValue, x, TestResource.getResource("R_outputParamFailed")); } - Class[] smallint_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, + Class[] smallint_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigDecimal.class, String.class}; for (int i = 0; i < smallint_coercions.length; i++) { Object smallIntValue = getxxx(3, smallint_coercions[i], callableStatement); @@ -1919,7 +1894,7 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() assertEquals(smallIntValue, x, TestResource.getResource("R_outputParamFailed")); } - Class[] int_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, + Class[] int_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigDecimal.class, String.class}; for (int i = 0; i < int_coercions.length; i++) { Object IntValue = getxxx(4, int_coercions[i], callableStatement); @@ -1932,8 +1907,8 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() } } - Class[] bigint_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, - BigDecimal.class, String.class}; + Class[] bigint_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, + Double.class, BigDecimal.class, String.class}; for (int i = 0; i < int_coercions.length; i++) { Object bigIntValue = getxxx(5, bigint_coercions[i], callableStatement); Object x = createValue(bigint_coercions[i], 4); @@ -1945,8 +1920,8 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() } } - Class[] float_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, - BigDecimal.class, String.class}; + Class[] float_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, + Double.class, BigDecimal.class, String.class}; for (int i = 0; i < float_coercions.length; i++) { Object floatDefaultValue = getxxx(6, float_coercions[i], callableStatement); Object x = createValue(float_coercions[i], 5); @@ -1969,7 +1944,7 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() } } - Class[] real_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, + Class[] real_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, BigDecimal.class, String.class}; for (int i = 0; i < real_coercions.length; i++) { @@ -1984,7 +1959,7 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() } } - Class[] decimalDefault_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, + Class[] decimalDefault_coercions = {Object.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigDecimal.class, String.class}; for (int i = 0; i < decimalDefault_coercions.length; i++) { Object decimalDefaultValue = getxxx(9, decimalDefault_coercions[i], callableStatement); @@ -2074,11 +2049,11 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } - private Object createValue(Class coercion, int index) { + private Object createValue(Class coercion, int index) { try { if (coercion == Float.class) return Float.parseFloat(numericValues[index]); @@ -2100,7 +2075,7 @@ private Object createValue(Class coercion, int index) { return null; } - private Object getxxx(int ordinal, Class coercion, + private Object getxxx(int ordinal, Class coercion, SQLServerCallableStatement callableStatement) throws SQLException { if (coercion == null || coercion == Object.class) { @@ -2146,8 +2121,8 @@ private void createOutputProcedureBinary() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) @@ -2155,7 +2130,7 @@ private void createOutputProcedureBinary() throws SQLException { + " @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); + + AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE); stmt.execute(sql); } @@ -2163,8 +2138,7 @@ private void createOutputProcedureBinary() throws SQLException { private void testOutputProcedureBinaryInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2206,14 +2180,13 @@ private void testOutputProcedureBinaryInorder(String sql) throws SQLException { assertEquals(received5[i], expected[i], TestResource.getResource("R_outputParamFailed")); } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedureBinaryInorderObject(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2242,20 +2215,19 @@ private void testOutputProcedureBinaryInorderObject(String sql) throws SQLExcept } } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } finally { index++; } } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedureBinaryInorderString(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2285,7 +2257,7 @@ private void testOutputProcedureBinaryInorderString(String sql) throws SQLExcept assertEquals(stringValue1.startsWith(expectedStr), true, "\nDecryption failed with getString(): " + stringValue1 + ".\nExpected Value: " + expectedStr); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } finally { index++; } @@ -2294,68 +2266,69 @@ private void testOutputProcedureBinaryInorderString(String sql) throws SQLExcept } protected static void createDateTableCallableStatement() throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + "PlainDate date null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " (" + + "PlainDate date null," + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDate date ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetime2Default datetime2 null," + "RandomizedDatetime2Default datetime2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetime2Default datetime2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetimeoffsetDefault datetimeoffset null," + "RandomizedDatetimeoffsetDefault datetimeoffset ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetimeoffsetDefault datetimeoffset ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainTimeDefault time null," + "RandomizedTimeDefault time ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTimeDefault time ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetime2 datetime2(2) null," + "RandomizedDatetime2 datetime2(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetime2 datetime2(2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainTime time(2) null," + "RandomizedTime time(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTime time(2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDatetimeoffset datetimeoffset(2) null," + "RandomizedDatetimeoffset datetimeoffset(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDatetimeoffset datetimeoffset(2) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainDateTime DateTime null," + "RandomizedDateTime DateTime ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicDateTime DateTime ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "PlainSmallDatetime smalldatetime null," + "RandomizedSmallDatetime smalldatetime ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicSmallDatetime smalldatetime ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + ");"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -2368,7 +2341,6 @@ private static LinkedList createTemporalTypesCallableStatement(boolean n Timestamp datetime2_2 = RandomData.generateDatetime2(2, nullable); Time time_2 = RandomData.generateTime(2, nullable); DateTimeOffset datetimeoffset_2 = RandomData.generateDatetimeoffset(2, nullable); - Timestamp datetime = RandomData.generateDatetime(nullable); Timestamp smalldatetime = RandomData.generateSmalldatetime(nullable); @@ -2387,11 +2359,10 @@ private static LinkedList createTemporalTypesCallableStatement(boolean n } private static void populateDateNormalCase() throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -2448,8 +2419,8 @@ private void createOutputProcedureDate() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate) @@ -2463,7 +2434,7 @@ private void createOutputProcedureDate() throws SQLException { + " @p4=PlainDateTime,@p41=DeterministicDateTime, @p5=PlainSmallDateTime,@p51=RandomizedSmallDateTime, " + " @p6=PlainDatetime2,@p61=RandomizedDatetime2, @p7=PlainTime,@p71=Deterministictime, " + " @p8=PlainDatetimeoffset, @p81=RandomizedDatetimeoffset" + " FROM " - + AbstractSQLGenerator.escapeIdentifier(dateTable); + + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE); stmt.execute(sql); } @@ -2471,8 +2442,7 @@ private void createOutputProcedureDate() throws SQLException { private void testOutputProcedureDateInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2498,13 +2468,10 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { assertEquals(callableStatement.getDate(1), callableStatement.getDate(2), TestResource.getResource("R_outputParamFailed")); - assertEquals(callableStatement.getTimestamp(3), callableStatement.getTimestamp(4), TestResource.getResource("R_outputParamFailed")); - assertEquals(callableStatement.getDateTimeOffset(5), callableStatement.getDateTimeOffset(6), TestResource.getResource("R_outputParamFailed")); - assertEquals(callableStatement.getTime(7), callableStatement.getTime(8), TestResource.getResource("R_outputParamFailed")); assertEquals(callableStatement.getDateTime(9), // actual plain @@ -2520,14 +2487,13 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testOutputProcedureDateInorderObject(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2553,13 +2519,10 @@ private void testOutputProcedureDateInorderObject(String sql) throws SQLExceptio assertEquals(callableStatement.getObject(1), callableStatement.getObject(2), TestResource.getResource("R_outputParamFailed")); - assertEquals(callableStatement.getObject(3), callableStatement.getObject(4), TestResource.getResource("R_outputParamFailed")); - assertEquals(callableStatement.getObject(5), callableStatement.getObject(6), TestResource.getResource("R_outputParamFailed")); - assertEquals(callableStatement.getObject(7), callableStatement.getObject(8), TestResource.getResource("R_outputParamFailed")); assertEquals(callableStatement.getObject(9), // actual plain @@ -2575,7 +2538,7 @@ private void testOutputProcedureDateInorderObject(String sql) throws SQLExceptio TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -2584,8 +2547,8 @@ private void createOutputProcedureBatch() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); // If a procedure contains more than one SQL statement, it is considered @@ -2604,8 +2567,7 @@ private void createOutputProcedureBatch() throws SQLException { private void testOutputProcedureBatchInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2627,7 +2589,7 @@ private void testOutputProcedureBatchInorder(String sql) throws SQLException { BigDecimal smallmoneyValue = callableStatement.getSmallMoney(4); assertEquals("" + smallmoneyValue, numericValues[12], TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -2636,8 +2598,8 @@ private void createOutputProcedure4() throws SQLException { + 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()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "create procedure " + AbstractSQLGenerator.escapeIdentifier(outputProcedure4) @@ -2659,8 +2621,8 @@ private void createMixedProcedureDateScale() throws SQLException { + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale) @@ -2669,7 +2631,7 @@ private void createMixedProcedureDateScale() throws SQLException { + " AS" + " SELECT top 1 @p1=DeterministicDatetime2,@p2=RandomizedDatetime2,@p3=DeterministicTime,@p4=RandomizedTime," + " @p5=DeterministicDatetimeoffset,@p6=RandomizedDatetimeoffset " + " FROM " - + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + + AbstractSQLGenerator.escapeIdentifier(Constants.SCALE_DATE_TABLE_AE) + " where DeterministicDatetime2 = @p1 and DeterministicTime = @p3 and DeterministicDatetimeoffset=@p5"; stmt.execute(sql); @@ -2678,8 +2640,7 @@ private void createMixedProcedureDateScale() throws SQLException { private void testMixedProcedureDateScaleInorder(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2704,14 +2665,13 @@ private void testMixedProcedureDateScaleInorder(String sql) throws SQLException TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils .getCallableStmt(con, sql, stmtColEncSetting)) { @@ -2736,7 +2696,7 @@ private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQL TestResource.getResource("R_outputParamFailed")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } } 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 c7d1cd3f5..99a4da078 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java @@ -7,7 +7,6 @@ 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; @@ -26,6 +25,8 @@ import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; /** @@ -54,8 +55,8 @@ public class JDBCEncryptionDecryptionTest extends AESetup { */ @Test public void testCharSpecificSetter() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { charValues = createCharValues(nullable); dropTables(stmt); createCharTable(); @@ -72,8 +73,8 @@ public void testCharSpecificSetter() throws SQLException { */ @Test public void testCharSetObject() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { charValues = createCharValues(nullable); dropTables(stmt); createCharTable(); @@ -91,8 +92,8 @@ public void testCharSetObject() throws SQLException { @Test public void testCharSetObjectWithJDBCTypes() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { charValues = createCharValues(nullable); dropTables(stmt); createCharTable(); @@ -109,8 +110,8 @@ public void testCharSetObjectWithJDBCTypes() throws SQLException { */ @Test public void testCharSpecificSetterNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; dropTables(stmt); createCharTable(); @@ -127,8 +128,8 @@ public void testCharSpecificSetterNull() throws SQLException { */ @Test public void testCharSetObjectNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; dropTables(stmt); createCharTable(); @@ -145,8 +146,8 @@ public void testCharSetObjectNull() throws SQLException { */ @Test public void testCharSetNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; dropTables(stmt); createCharTable(); @@ -163,8 +164,8 @@ public void testCharSetNull() throws SQLException { */ @Test public void testBinarySpecificSetter() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { LinkedList byteValues = createbinaryValues(false); dropTables(stmt); createBinaryTable(); @@ -181,8 +182,8 @@ public void testBinarySpecificSetter() throws SQLException { */ @Test public void testBinarySetobject() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { byteValuesSetObject = createbinaryValues(false); dropTables(stmt); createBinaryTable(); @@ -199,8 +200,8 @@ public void testBinarySetobject() throws SQLException { */ @Test public void testBinarySetNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { byteValuesNull = createbinaryValues(true); dropTables(stmt); createBinaryTable(); @@ -217,8 +218,8 @@ public void testBinarySetNull() throws SQLException { */ @Test public void testBinarySpecificSetterNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { byteValuesNull = createbinaryValues(true); dropTables(stmt); createBinaryTable(); @@ -235,8 +236,8 @@ public void testBinarySpecificSetterNull() throws SQLException { */ @Test public void testBinarysetObjectNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { byteValuesNull = createbinaryValues(true); dropTables(stmt); createBinaryTable(); @@ -254,8 +255,8 @@ public void testBinarysetObjectNull() throws SQLException { @Test public void testBinarySetObjectWithJDBCTypes() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { byteValuesSetObject = createbinaryValues(false); dropTables(stmt); createBinaryTable(); @@ -272,8 +273,8 @@ public void testBinarySetObjectWithJDBCTypes() throws SQLException { */ @Test public void testDateSpecificSetter() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dateValues = createTemporalTypes(nullable); dropTables(stmt); createDateTable(); @@ -290,8 +291,8 @@ public void testDateSpecificSetter() throws SQLException { */ @Test public void testDateSetObject() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dateValues = createTemporalTypes(nullable); dropTables(stmt); createDateTable(); @@ -308,8 +309,8 @@ public void testDateSetObject() throws SQLException { */ @Test public void testDateSetObjectWithJavaType() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dateValues = createTemporalTypes(nullable); dropTables(stmt); createDateTable(); @@ -326,8 +327,8 @@ public void testDateSetObjectWithJavaType() throws SQLException { */ @Test public void testDateSetObjectWithJDBCType() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dateValues = createTemporalTypes(nullable); dropTables(stmt); createDateTable(); @@ -344,8 +345,8 @@ public void testDateSetObjectWithJDBCType() throws SQLException { */ @Test public void testDateSpecificSetterMinMaxValue() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { RandomData.returnMinMax = true; dateValues = createTemporalTypes(nullable); dropTables(stmt); @@ -363,8 +364,8 @@ public void testDateSpecificSetterMinMaxValue() throws SQLException { */ @Test public void testDateSetNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { RandomData.returnNull = true; nullable = true; @@ -390,8 +391,8 @@ public void testDateSetObjectNull() throws SQLException { RandomData.returnNull = true; nullable = true; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dateValues = createTemporalTypes(nullable); dropTables(stmt); createDateTable(); @@ -415,8 +416,8 @@ public void testNumericSpecificSetter() throws TestAbortedException, Exception { numericValues2 = new String[numericValues.length]; System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); createNumericTable(); populateNumeric(numericValues); @@ -436,8 +437,8 @@ public void testNumericSetObject() throws SQLException { numericValues2 = new String[numericValues.length]; System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); createNumericTable(); populateNumericSetObject(numericValues); @@ -454,8 +455,8 @@ public void testNumericSetObject() throws SQLException { @Test public void testNumericSetObjectWithJDBCTypes() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { numericValues = createNumericValues(nullable); numericValues2 = new String[numericValues.length]; System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); @@ -475,17 +476,17 @@ public void testNumericSetObjectWithJDBCTypes() throws SQLException { */ @Test public void testNumericSpecificSetterMaxValue() throws SQLException { - String[] numericValuesBoundaryPositive = {"true", "255", "32767", "2147483647", "9223372036854775807", - "1.79E308", "1.123", "3.4E38", "999999999999999999", "12345.12345", "999999999999999999", "567812.78", - "214748.3647", "922337203685477.5807", "999999999999999999999999.9999", - "999999999999999999999999.9999"}; - String[] numericValuesBoundaryPositive2 = {"true", "255", "32767", "2147483647", "9223372036854775807", - "1.79E308", "1.123", "3.4E38", "999999999999999999", "12345.12345", "999999999999999999", "567812.78", - "214748.3647", "922337203685477.5807", "999999999999999999999999.9999", - "999999999999999999999999.9999"}; - - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] numericValuesBoundaryPositive = {Boolean.TRUE.toString(), "255", "32767", "2147483647", + "9223372036854775807", "1.79E308", "1.123", "3.4E38", "999999999999999999", "12345.12345", + "999999999999999999", "567812.78", "214748.3647", "922337203685477.5807", + "999999999999999999999999.9999", "999999999999999999999999.9999"}; + String[] numericValuesBoundaryPositive2 = {Boolean.TRUE.toString(), "255", "32767", "2147483647", + "9223372036854775807", "1.79E308", "1.123", "3.4E38", "999999999999999999", "12345.12345", + "999999999999999999", "567812.78", "214748.3647", "922337203685477.5807", + "999999999999999999999999.9999", "999999999999999999999999.9999"}; + + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); createNumericTable(); populateNumeric(numericValuesBoundaryPositive); @@ -501,17 +502,17 @@ public void testNumericSpecificSetterMaxValue() throws SQLException { */ @Test public void testNumericSpecificSetterMinValue() throws SQLException { - String[] numericValuesBoundaryNegtive = {"false", "0", "-32768", "-2147483648", "-9223372036854775808", - "-1.79E308", "1.123", "-3.4E38", "999999999999999999", "12345.12345", "999999999999999999", "567812.78", - "-214748.3648", "-922337203685477.5808", "999999999999999999999999.9999", - "999999999999999999999999.9999"}; - String[] numericValuesBoundaryNegtive2 = {"false", "0", "-32768", "-2147483648", "-9223372036854775808", - "-1.79E308", "1.123", "-3.4E38", "999999999999999999", "12345.12345", "999999999999999999", "567812.78", - "-214748.3648", "-922337203685477.5808", "999999999999999999999999.9999", - "999999999999999999999999.9999"}; - - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] numericValuesBoundaryNegtive = {Boolean.FALSE.toString(), "0", "-32768", "-2147483648", + "-9223372036854775808", "-1.79E308", "1.123", "-3.4E38", "999999999999999999", "12345.12345", + "999999999999999999", "567812.78", "-214748.3648", "-922337203685477.5808", + "999999999999999999999999.9999", "999999999999999999999999.9999"}; + String[] numericValuesBoundaryNegtive2 = {Boolean.FALSE.toString(), "0", "-32768", "-2147483648", + "-9223372036854775808", "-1.79E308", "1.123", "-3.4E38", "999999999999999999", "12345.12345", + "999999999999999999", "567812.78", "-214748.3648", "-922337203685477.5808", + "999999999999999999999999.9999", "999999999999999999999999.9999"}; + + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); createNumericTable(); populateNumeric(numericValuesBoundaryNegtive); @@ -533,8 +534,8 @@ public void testNumericSpecificSetterNull() throws SQLException { numericValuesNull2 = new String[numericValuesNull.length]; System.arraycopy(numericValuesNull, 0, numericValuesNull2, 0, numericValuesNull.length); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); createNumericTable(); populateNumericNullCase(numericValuesNull); @@ -559,8 +560,8 @@ public void testNumericSpecificSetterSetObjectNull() throws SQLException { numericValuesNull2 = new String[numericValuesNull.length]; System.arraycopy(numericValuesNull, 0, numericValuesNull2, 0, numericValuesNull.length); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); createNumericTable(); populateNumericSetObjectNull(); @@ -579,15 +580,15 @@ public void testNumericSpecificSetterSetObjectNull() throws SQLException { */ @Test public void testNumericNormalization() throws SQLException { - String[] numericValuesNormalization = {"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"}; - 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"}; - - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] numericValuesNormalization = {Boolean.TRUE.toString(), "1", "127", "100", "100", "1.123", "1.123", + "1.123", "123456789123456789", "12345.12345", "987654321123456789", "567812.78", "7812.7812", + "7812.7812", "999999999999999999999999.9999", "999999999999999999999999.9999"}; + String[] numericValuesNormalization2 = {Boolean.TRUE.toString(), "1", "127", "100", "100", "1.123", "1.123", + "1.123", "123456789123456789", "12345.12345", "987654321123456789", "567812.78", "7812.7812", + "7812.7812", "999999999999999999999999.9999", "999999999999999999999999.9999"}; + + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); createNumericTable(); populateNumericNormalCase(numericValuesNormalization); @@ -597,9 +598,8 @@ public void testNumericNormalization() throws SQLException { } private void testChar(SQLServerStatement stmt, String[] values) throws SQLException { - String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(charTable); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { @@ -614,10 +614,9 @@ private void testChar(SQLServerStatement stmt, String[] values) throws SQLExcept } private void testBinary(SQLServerStatement stmt, LinkedList values) throws SQLException { - String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(binaryTable); + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.BINARY_TABLE_AE); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { @@ -632,10 +631,9 @@ private void testBinary(SQLServerStatement stmt, LinkedList values) thro } private void testDate(SQLServerStatement stmt, LinkedList values1) throws SQLException { - String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(dateTable); + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { @@ -747,16 +745,16 @@ private void testGetBigDecimal(ResultSet rs, int numberOfColumns, String[] value String decimalValue2 = "" + rs.getBigDecimal(i + 1); String decimalValue3 = "" + rs.getBigDecimal(i + 2); - if (decimalValue1.equalsIgnoreCase("0") - && (values[index].equalsIgnoreCase("true") || values[index].equalsIgnoreCase("false"))) { - decimalValue1 = "false"; - decimalValue2 = "false"; - decimalValue3 = "false"; - } else if (decimalValue1.equalsIgnoreCase("1") - && (values[index].equalsIgnoreCase("true") || values[index].equalsIgnoreCase("false"))) { - decimalValue1 = "true"; - decimalValue2 = "true"; - decimalValue3 = "true"; + if (decimalValue1.equalsIgnoreCase("0") && (values[index].equalsIgnoreCase(Boolean.TRUE.toString()) + || values[index].equalsIgnoreCase(Boolean.FALSE.toString()))) { + decimalValue1 = Boolean.FALSE.toString(); + decimalValue2 = Boolean.FALSE.toString(); + decimalValue3 = Boolean.FALSE.toString(); + } else if (decimalValue1.equalsIgnoreCase("1") && (values[index].equalsIgnoreCase(Boolean.TRUE.toString()) + || values[index].equalsIgnoreCase(Boolean.FALSE.toString()))) { + decimalValue1 = Boolean.TRUE.toString(); + decimalValue2 = Boolean.TRUE.toString(); + decimalValue3 = Boolean.TRUE.toString(); } if (null != values[index]) { @@ -795,16 +793,16 @@ private void testGetString(ResultSet rs, int numberOfColumns, String[] values) t String stringValue2 = ("" + rs.getString(i + 1)).trim(); String stringValue3 = ("" + rs.getString(i + 2)).trim(); - if (stringValue1.equalsIgnoreCase("0") - && (values[index].equalsIgnoreCase("true") || values[index].equalsIgnoreCase("false"))) { - stringValue1 = "false"; - stringValue2 = "false"; - stringValue3 = "false"; - } else if (stringValue1.equalsIgnoreCase("1") - && (values[index].equalsIgnoreCase("true") || values[index].equalsIgnoreCase("false"))) { - stringValue1 = "true"; - stringValue2 = "true"; - stringValue3 = "true"; + if (stringValue1.equalsIgnoreCase("0") && (values[index].equalsIgnoreCase(Boolean.TRUE.toString()) + || values[index].equalsIgnoreCase(Boolean.FALSE.toString()))) { + stringValue1 = Boolean.FALSE.toString(); + stringValue2 = Boolean.FALSE.toString(); + stringValue3 = Boolean.FALSE.toString(); + } else if (stringValue1.equalsIgnoreCase("1") && (values[index].equalsIgnoreCase(Boolean.TRUE.toString()) + || values[index].equalsIgnoreCase(Boolean.FALSE.toString()))) { + stringValue1 = Boolean.TRUE.toString(); + stringValue2 = Boolean.TRUE.toString(); + stringValue3 = Boolean.TRUE.toString(); } try { @@ -1016,10 +1014,9 @@ private void testGetDate(ResultSet rs, int numberOfColumns, LinkedList v } private void testNumeric(Statement stmt, String[] numericValues, boolean isNull) throws SQLException { - String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable); + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { try (SQLServerResultSet rs = (stmt == null) ? (SQLServerResultSet) pstmt.executeQuery() @@ -1032,8 +1029,8 @@ private void testNumeric(Statement stmt, String[] numericValues, boolean isNull) if (!isNull) testWithSpecifiedtype(rs, numberOfColumns, numericValues); else { - String[] nullNumericValues = {"false", "0", "0", "0", "0", "0.0", "0.0", "0.0", null, null, - null, null, null, null, null, null}; + String[] nullNumericValues = {Boolean.FALSE.toString(), "0", "0", "0", "0", "0.0", "0.0", "0.0", + null, null, null, null, null, null, null, null}; testWithSpecifiedtype(rs, numberOfColumns, nullNumericValues); } } 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 7a343047f..804d236a9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -7,7 +7,6 @@ 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; @@ -28,6 +27,8 @@ import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; /** @@ -65,8 +66,8 @@ public class PrecisionScaleTest extends AESetup { @Test public void testNumericPrecision8Scale2() throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); String[] numeric = {"1.12345", "12345.12", "567.70"}; @@ -81,8 +82,8 @@ public void testNumericPrecision8Scale2() throws Exception { @Test public void testDateScale2() throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); String[] dateNormalCase = {GMTDate + ".18", GMTDate + ".1770000", @@ -101,8 +102,8 @@ public void testDateScale2() throws Exception { @Test public void testNumericPrecision8Scale0() throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); String[] numeric2 = {"1.12345", "12345", "567"}; @@ -117,8 +118,8 @@ public void testNumericPrecision8Scale0() throws Exception { @Test public void testDateScale0() throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); String[] dateNormalCase2 = {GMTDate, GMTDate + ".1770000", dateTimeOffsetExpectedValue + ".1770000 +00:01", @@ -136,8 +137,8 @@ public void testDateScale0() throws Exception { @Test public void testNumericPrecision8Scale2Null() throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); String[] numericNull = {"null", "null", "null"}; @@ -151,8 +152,8 @@ public void testNumericPrecision8Scale2Null() throws Exception { @Test public void testDateScale2Null() throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; @@ -166,8 +167,8 @@ public void testDateScale2Null() throws Exception { @Test public void testDateScale5Null() throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropTables(stmt); String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; @@ -180,10 +181,9 @@ public void testDateScale5Null() throws Exception { private void testNumeric(String[] numeric) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable))) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); ResultSet rs = stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE))) { int numberOfColumns = rs.getMetaData().getColumnCount(); ArrayList skipMax = new ArrayList<>(); @@ -198,9 +198,9 @@ private void testNumeric(String[] numeric) throws SQLException { private void testDate(String[] dateNormalCase, String[] dateSetObject) throws Exception { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(dateTable))) { + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); ResultSet rs = stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE))) { int numberOfColumns = rs.getMetaData().getColumnCount(); ArrayList skipMax = new ArrayList<>(); @@ -365,11 +365,10 @@ private void testGetDate(ResultSet rs, int numberOfColumns, String[] dates) thro } private void populateDateNormalCase(int scale) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -409,11 +408,10 @@ private void populateDateNormalCase(int scale) throws SQLException { } private void populateDateNormalCaseNull(int scale) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -452,11 +450,10 @@ private void populateDateNormalCaseNull(int scale) throws SQLException { } private void populateNumericNormalCase(String[] numeric, int precision, int scale) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -480,11 +477,10 @@ private void populateNumericNormalCase(String[] numeric, int precision, int scal } private void populateNumericSetObject(String[] numeric, int precision, int scale) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -509,11 +505,10 @@ private void populateNumericSetObject(String[] numeric, int precision, int scale } private void populateNumericSetObjectNull(int precision, int scale) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -538,11 +533,10 @@ private void populateNumericSetObjectNull(int precision, int scale) throws SQLEx } private void populateDateSetObject(int scale) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -583,11 +577,10 @@ private void populateDateSetObject(int scale) throws SQLException { } private void populateDateSetObjectNull(int scale) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, - AEInfo); + try (SQLServerConnection con = PrepUtil.getConnection(AETestConnectionString, AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java index d6b9ee120..de5eff03d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java @@ -7,8 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.Connection; -import java.sql.Date; -import java.sql.DriverManager; import java.sql.JDBCType; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -19,22 +17,18 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; -import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) public class RegressionAlwaysEncryptedTest extends AESetup { - static final String dateTable = RandomUtil.getIdentifier("JDBCEncryptedDate"); - static final String charTable = RandomUtil.getIdentifier("JDBCEncryptedChar"); - static final String numericTable = RandomUtil.getIdentifier("JDBCEncryptedNumeric"); - - static final Date date = new Date(new java.util.Date().getTime()); @Test public void alwaysEncrypted1() throws SQLException { - try (Connection connection = DriverManager.getConnection( + try (Connection connection = PrepUtil.getConnection( connectionString + ";trustservercertificate=true;columnEncryptionSetting=enabled;", AEInfo); Statement stmt = connection.createStatement()) { dropTables(stmt); @@ -59,7 +53,7 @@ public void alwaysEncrypted1() throws SQLException { @Test public void alwaysEncrypted2() throws SQLException { - try (Connection connection = DriverManager.getConnection( + try (Connection connection = PrepUtil.getConnection( connectionString + ";trustservercertificate=true;columnEncryptionSetting=enabled;", AEInfo); Statement stmt = connection.createStatement()) { dropTables(stmt); @@ -83,17 +77,18 @@ public void alwaysEncrypted2() throws SQLException { } private void populateDateTable(Connection connection) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " values( " + "?" + + ")"; try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { - sqlPstmt.setObject(1, date); + sqlPstmt.setObject(1, Constants.DATE); sqlPstmt.executeUpdate(); } } private void populateCharTable(Connection connection) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?,?,?,?" - + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " values( " + + "?,?,?,?,?,?" + ")"; try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { sqlPstmt.setObject(1, "hi"); @@ -107,7 +102,7 @@ private void populateCharTable(Connection connection) throws SQLException { } private void populateNumericTable(Connection connection) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values(?,?,?,?,?,?,?,?,?)"; try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { @@ -126,7 +121,7 @@ private void populateNumericTable(Connection connection) throws SQLException { } private void populateNumericTableSpecificSetter(Connection connection) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + "?,?,?,?,?,?,?,?,?" + ")"; try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { @@ -145,8 +140,8 @@ private void populateNumericTableSpecificSetter(Connection connection) throws SQ } private void populateNumericTableWithNull(Connection connection) throws SQLException { - String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?" - + ",?,?,?" + ",?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " values( " + + "?,?,?" + ",?,?,?" + ",?,?,?" + ")"; try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { sqlPstmt.setObject(1, null, java.sql.Types.BIT); @@ -164,7 +159,8 @@ private void populateNumericTableWithNull(Connection connection) throws SQLExcep private void verifyDateTable(Connection connection) throws SQLException { try (Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(dateTable))) { + ResultSet rs = stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE))) { while (rs.next()) { // VSTS BUG 5268 // assertEquals(date.getTime(), ((Date) rs.getObject(1)).getTime()); @@ -174,7 +170,8 @@ private void verifyDateTable(Connection connection) throws SQLException { private void verifyCharTable(Connection connection) throws SQLException { try (Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(charTable))) { + ResultSet rs = stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE))) { while (rs.next()) { assertEquals("hi ", rs.getObject(1)); assertEquals("sample ", rs.getObject(2)); @@ -188,8 +185,8 @@ private void verifyCharTable(Connection connection) throws SQLException { private void verifyNumericTable(Connection connection, boolean isNull) throws SQLException { try (Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable))) { + ResultSet rs = stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE))) { while (rs.next()) { if (isNull) { assertEquals(null, rs.getObject(1)); @@ -217,46 +214,47 @@ private void verifyNumericTable(Connection connection, boolean isNull) throws SQ } private void createDateTable(Statement stmt) throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE) + " (" + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + ");"; + + Constants.CEK_NAME + ") NULL," + ");"; stmt.execute(sql); } private void createCharTable(Statement stmt) throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE) + " (" + "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," + + Constants.CEK_NAME + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "PlainVarchar varchar(50) null," + + Constants.CEK_NAME + ") NULL," + "PlainVarchar varchar(50) null," + "RandomizedVarchar varchar(50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "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," + ");"; + + Constants.CEK_NAME + ") NULL," + ");"; stmt.execute(sql); } private void createNumericTable(Statement stmt) throws SQLException { - String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainBit bit null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE) + " (" + + "PlainBit bit null," + "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "PlainTinyint tinyint null," + + Constants.CEK_NAME + ") NULL," + "PlainTinyint tinyint null," + "RandomizedTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + "PlainSmallint smallint null," + + Constants.CEK_NAME + ") NULL," + "PlainSmallint smallint null," + "RandomizedSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + + Constants.CEK_NAME + ") NULL," + "DeterministicSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - + cekName + ") NULL," + ");"; + + Constants.CEK_NAME + ") NULL," + ");"; stmt.execute(sql); } public static void dropTables(Statement stmt) throws SQLException { - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateTable), stmt); - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), stmt); - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.DATE_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.CHAR_TABLE_AE), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(Constants.NUMERIC_TABLE_AE), stmt); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java b/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java index 44388eea1..df3bf4df3 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/JDBC43Test.java @@ -4,22 +4,13 @@ */ package com.microsoft.sqlserver.jdbc; -import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assumptions.assumeTrue; -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverManager; import java.sql.JDBCType; import java.sql.SQLException; import java.sql.ShardingKey; -import java.util.Enumeration; -import java.util.stream.Stream; - import javax.sql.ConnectionPoolDataSource; -import javax.sql.PooledConnection; -import javax.sql.XAConnection; - +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -33,6 +24,7 @@ * */ @RunWith(JUnitPlatform.class) +@Tag("AzureDWTest") public class JDBC43Test extends AbstractTest { ShardingKey superShardingKey = null; ShardingKey shardingKey = null; @@ -62,7 +54,7 @@ public void connectionBuilderTest() throws TestAbortedException, SQLException { } try { - Connection con = ds.createConnectionBuilder().user("rafa").password("tennis").shardingKey(shardingKey) + ds.createConnectionBuilder().user("rafa").password("tennis").shardingKey(shardingKey) .superShardingKey(superShardingKey).build(); } catch (SQLException e) { assert (e.getMessage().contains(TestResource.getResource("R_notImplemented"))); @@ -94,7 +86,7 @@ public void xaConnectionBuilderTest() throws TestAbortedException, SQLException } try { - XAConnection con = ds.createXAConnectionBuilder().user("rafa").password("tennis").shardingKey(shardingKey) + ds.createXAConnectionBuilder().user("rafa").password("tennis").shardingKey(shardingKey) .superShardingKey(superShardingKey).build(); } catch (SQLException e) { assert (e.getMessage().contains(TestResource.getResource("R_notImplemented"))); @@ -124,8 +116,8 @@ public void connectionPoolDataSourceTest() throws TestAbortedException, SQLExcep assert (e.getMessage().contains(TestResource.getResource("R_notImplemented"))); } try { - PooledConnection con = ds.createPooledConnectionBuilder().user("rafa").password("tennis") - .shardingKey(shardingKey).superShardingKey(superShardingKey).build(); + ds.createPooledConnectionBuilder().user("rafa").password("tennis").shardingKey(shardingKey) + .superShardingKey(superShardingKey).build(); } catch (SQLException e) { assert (e.getMessage().contains(TestResource.getResource("R_notImplemented"))); } @@ -141,7 +133,7 @@ public void connectionPoolDataSourceTest() throws TestAbortedException, SQLExcep @Test public void setShardingKeyIfValidTest() throws TestAbortedException, SQLException { assumeTrue(TestUtils.supportJDBC43(connection)); - try (SQLServerConnection connection43 = (SQLServerConnection43) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection connection43 = (SQLServerConnection43) getConnection()) { try { connection43.setShardingKeyIfValid(shardingKey, 10); } catch (SQLException e) { @@ -165,7 +157,7 @@ public void setShardingKeyIfValidTest() throws TestAbortedException, SQLExceptio @Test public void setShardingKeyTest() throws TestAbortedException, SQLException { assumeTrue(TestUtils.supportJDBC43(connection)); - try (SQLServerConnection connection43 = (SQLServerConnection43) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection connection43 = (SQLServerConnection43) getConnection()) { try { connection43.setShardingKey(shardingKey); } catch (SQLException e) { @@ -178,39 +170,4 @@ public void setShardingKeyTest() throws TestAbortedException, SQLException { } } } - - /** - * Tests the stream drivers() methods in java.sql.DriverManager - * - * @since 1.9 - * @throws ClassNotFoundException - */ - @Test - public void driversTest() throws ClassNotFoundException { - Stream drivers = DriverManager.drivers(); - Object[] driversArray = drivers.toArray(); - assertEquals(driversArray[0].getClass(), Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")); - } - - /** - * Tests deregister Driver - * - * @throws SQLException - * @throws ClassNotFoundException - */ - @Test - public void deregisterDriverTest() throws SQLException, ClassNotFoundException { - Enumeration drivers = DriverManager.getDrivers(); - Driver current = null; - while (drivers.hasMoreElements()) { - current = drivers.nextElement(); - DriverManager.deregisterDriver(current); - } - Stream currentDrivers = DriverManager.drivers(); - Object[] driversArray = currentDrivers.toArray(); - assertEquals(0, driversArray.length); - - DriverManager.registerDriver(current); - } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/RandomData.java b/src/test/java/com/microsoft/sqlserver/jdbc/RandomData.java index f091f8f00..c376bdd16 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/RandomData.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/RandomData.java @@ -30,9 +30,7 @@ public class RandomData { private static String specicalCharSet = "ÀÂÃÄËßîðÐ"; private static String normalCharSet = "1234567890-=!@#$%^&*()_+qwertyuiop[]\\asdfghjkl;'zxcvbnm,./QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?"; - private static String unicodeCharSet = "♠♣♥♦林花謝了春紅太匆匆無奈朝我附件为放假哇额外放我放问역사적으로본래한민족의영역은만주와연해주의일부를포함하였으나会和太空特工我來寒雨晚來風胭脂淚留人醉幾時重自是人生長恨水長東ྱོགས་སུ་འཁོར་བའི་ས་ཟླུུམ་ཞིག་ལ་ངོས་འཛིན་དགོས་ཏེ།ངག་ཕྱོαβγδεζηθικλμνξοπρστυφχψ太陽系の年齢もまた隕石の年代測定に依拠するので"; - private static String numberCharSet = "1234567890"; private static String numberCharSet2 = "123456789"; diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/SQLServerDriverTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/SQLServerDriverTest.java new file mode 100644 index 000000000..337ab3154 --- /dev/null +++ b/src/test/java/com/microsoft/sqlserver/jdbc/SQLServerDriverTest.java @@ -0,0 +1,190 @@ +package com.microsoft.sqlserver.jdbc; + +import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.DriverPropertyInfo; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.sql.Statement; +import java.util.Enumeration; +import java.util.Properties; +import java.util.logging.Logger; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; + + +@RunWith(JUnitPlatform.class) +@Tag("AzureDWTest") +public class SQLServerDriverTest extends AbstractTest { + + String randomServer = RandomUtil.getIdentifier("Server"); + static final Logger logger = Logger.getLogger("SQLServerDriverTest"); + + /** + * Tests the stream drivers() methods in java.sql.DriverManager + * + * @since 1.9 + * @throws ClassNotFoundException + */ + @Test + public void testDriverDM() throws ClassNotFoundException { + Stream drivers = DriverManager.drivers(); + Object[] driversArray = drivers.toArray(); + assertEquals(driversArray[0].getClass(), Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerDriver"), + TestResource.getResource("R_parrentLoggerNameWrong")); + } + + /** + * Tests deRegister Driver + * + * @throws SQLException + * @throws ClassNotFoundException + */ + @Test + public void testDriverRegistrationDM() throws SQLException, ClassNotFoundException { + Enumeration drivers = DriverManager.getDrivers(); + Driver current = null; + while (drivers.hasMoreElements()) { + current = drivers.nextElement(); + DriverManager.deregisterDriver(current); + } + Stream currentDrivers = DriverManager.drivers(); + Object[] driversArray = currentDrivers.toArray(); + assertEquals(0, driversArray.length); + DriverManager.registerDriver(current); + } + + @Test + public void testDriverIsRegistered() { + assertTrue(SQLServerDriver.isRegistered(), TestResource.getResource("R_valuesAreDifferent")); + } + + @Test + public void testDriverRegistrationInternal() throws SQLException { + if (SQLServerDriver.isRegistered()) { + try { + SQLServerDriver.register(); + } catch (SQLException e) { + fail(e.getMessage()); + } + SQLServerDriver.deregister(); + SQLServerDriver.register(); + } + } + + @Test + public void testConnect() { + SQLServerDriver driver = new SQLServerDriver(); + try (Connection con = driver.connect(connectionString, null); Statement stmt = con.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT 1")) { + while (rs.next()) { + assertEquals(1, rs.getInt(1)); + } + } catch (SQLException e) { + fail(); + } + try (Connection con = driver.connect(null, null)) { + fail(); + } catch (SQLException e) { + assert (e instanceof SQLServerException); + assert (null != e.getMessage()); + assert (e.getMessage().contains(TestResource.getResource("R_ConnectionURLNull"))); + } + } + + @Test + public void testAcceptsUrl() throws SQLException { + SQLServerDriver driver = new SQLServerDriver(); + assert (driver.acceptsURL(connectionString)); + assert (!driver.acceptsURL("jdbc:somethingelse")); + try { + driver.acceptsURL(null); + fail(); + } catch (SQLException e) { + assert (e instanceof SQLServerException); + assert (null != e.getMessage()); + assert (e.getMessage().contains(TestResource.getResource("R_ConnectionURLNull"))); + } + } + + @Test + public void testJDBCCompliant() { + assert (new SQLServerDriver().jdbcCompliant()); + } + + @Test + public void testNullPropertyInfo() { + try { + new SQLServerDriver().getPropertyInfo(null, null); + fail(); + } catch (SQLException e) { + assert (e instanceof SQLServerException); + assert (null != e.getMessage()); + assert (e.getMessage().contains(TestResource.getResource("R_ConnectionURLNull"))); + } + } + + @Test + public void testParentLogger() throws SQLFeatureNotSupportedException { + SQLServerDriver serverDriver = new SQLServerDriver(); + Logger logger = serverDriver.getParentLogger(); + assertEquals(logger.getName(), Constants.MSSQL_JDBC_PACKAGE, + TestResource.getResource("R_parrentLoggerNameWrong")); + } + + /** + * test connection properties + * + * @throws SQLException + */ + @Test + public void testConnectionDriver() throws SQLException { + SQLServerDriver d = new SQLServerDriver(); + Properties info = new Properties(); + StringBuffer url = new StringBuffer(); + url.append(Constants.JDBC_PREFIX + randomServer + ";packetSize=512;"); + // test defaults + DriverPropertyInfo[] infoArray = d.getPropertyInfo(url.toString(), info); + for (DriverPropertyInfo anInfoArray1 : infoArray) { + logger.fine(anInfoArray1.name); + logger.fine(anInfoArray1.description); + logger.fine(Boolean.valueOf(anInfoArray1.required).toString()); + logger.fine(anInfoArray1.value); + } + + url.append("encrypt=true; trustStore=someStore; trustStorePassword=somepassword;"); + url.append("hostNameInCertificate=someHost; trustServerCertificate=true"); + infoArray = d.getPropertyInfo(url.toString(), info); + for (DriverPropertyInfo anInfoArray : infoArray) { + if (anInfoArray.name.equalsIgnoreCase(Constants.ENCRYPT)) { + assertTrue(anInfoArray.value.equalsIgnoreCase(Boolean.TRUE.toString()), + TestResource.getResource("R_valuesAreDifferent")); + } + if (anInfoArray.name.equalsIgnoreCase(Constants.TRUST_STORE)) { + assertTrue(anInfoArray.value.equalsIgnoreCase("someStore"), + TestResource.getResource("R_valuesAreDifferent")); + } + if (anInfoArray.name.equalsIgnoreCase(Constants.TRUST_STORE_PASSWORD)) { + assertTrue(anInfoArray.value.equalsIgnoreCase("somepassword"), + TestResource.getResource("R_valuesAreDifferent")); + } + if (anInfoArray.name.equalsIgnoreCase(Constants.HOST_NAME_IN_CERTIFICATE)) { + assertTrue(anInfoArray.value.equalsIgnoreCase("someHost"), + TestResource.getResource("R_valuesAreDifferent")); + } + } + } +} diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/SSLCertificateValidation.java b/src/test/java/com/microsoft/sqlserver/jdbc/SSLCertificateValidation.java index 101cfb4b2..5e0548938 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/SSLCertificateValidation.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/SSLCertificateValidation.java @@ -11,12 +11,14 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) +@Tag("AzureDWTest") public class SSLCertificateValidation { /** diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java index 13e1ad0d9..5b3ee675e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java @@ -7,6 +7,8 @@ import java.util.ListResourceBundle; +import com.microsoft.sqlserver.testframework.Constants; + /** * A simple resource bundle containing the strings for localizing. @@ -14,7 +16,7 @@ */ public final class TestResource extends ListResourceBundle { public static String getResource(String key) { - return TestResource.getBundle("com.microsoft.sqlserver.jdbc.TestResource").getString(key); + return TestResource.getBundle(Constants.MSSQL_JDBC_PACKAGE + ".TestResource").getString(key); } protected Object[][] getContents() { @@ -47,6 +49,7 @@ protected Object[][] getContents() { {"R_createDropAlterTableFailed", "Create/drop/alter table with preparedStatement failed!"}, {"R_grantFailed", "grant table with preparedStatement failed!"}, {"R_connectionIsClosed", "The connection is closed."}, + {"R_ConnectionURLNull", "The connection URL is null." }, {"R_connectionIsNotClosed", "The connection is not closed."}, {"R_invalidExceptionMessage", "Invalid exception message"}, {"R_failedValidate", "failed to validate values in $0} "}, {"R_tableNotDropped", "table not dropped. "}, @@ -125,7 +128,7 @@ protected Object[][] getContents() { {"R_noKeyStore", "Aborting test case as no java key store and alias name exists."}, {"R_badStreamLength", "The stream value is not the specified length. The specified length was"}, {"R_streamReadError", "An error occurred while reading the value from the stream object. Error"}, - {"R_SQLStateNull", "SQLState should not be null"}, {"R_blobFreed", "This Blob oject has been freed."}, + {"R_SQLStateNull", "SQLState should not be null"}, {"R_blobFreed", "This Blob object has been freed."}, {"R_streamNull", "Stream is null when data is not."}, {"R_incorrectUpdateCount", "Incorrect updateCount."}, {"R_testInterleaved", "Test interleaved inserts and warnings"}, {"R_errorFollowInserts", "Test error followed by inserts"}, @@ -169,5 +172,7 @@ protected Object[][] getContents() { {"R_incorrectColumnNumInsertDW", "Column name or number of supplied values does not match table definition."}, {"R_incorrectSyntaxTable", "Incorrect syntax near the keyword 'table'."}, - {"R_incorrectSyntaxTableDW", "Incorrect syntax near 'table'."},}; + {"R_incorrectSyntaxTableDW", "Incorrect syntax near 'table'."}, + {"R_ConnectionStringNull", "Connection String should not be null"}, + {"R_OperandTypeClash", "Operand type clash"}}; } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java index 48b1f0d30..8f4d06105 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java @@ -21,9 +21,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.sqlType.SqlBigInt; import com.microsoft.sqlserver.testframework.sqlType.SqlBinary; import com.microsoft.sqlserver.testframework.sqlType.SqlBit; @@ -59,40 +59,65 @@ * @since 6.1.2 */ public class TestUtils { - public static final Logger log = Logger.getLogger("TestUtils"); - - // 'SQL' represents SQL Server, while 'SQLAzure' represents SQL Azure. - public static final String SERVER_TYPE_SQL_SERVER = "SQL"; - public static final String SERVER_TYPE_SQL_AZURE = "SQLAzure"; - // private static SqlType types = null; private static ArrayList types = null; - - /** - * Returns serverType + private static final char[] HEXCHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', + 'F'}; + + final static int ENGINE_EDITION_FOR_SQL_AZURE = 5; + final static int ENGINE_EDITION_FOR_SQL_AZURE_DW = 6; + final static int ENGINE_EDITION_FOR_SQL_AZURE_MI = 8; + private static Boolean isAzure = null; + private static Boolean isAzureDW = null; + private static Boolean isAzureMI = null; + + /* + * SERVERPROPERTY('EngineEdition') can be used to determine whether the db server is SQL Azure. + * It should return 6 for SQL Azure DW. This is more reliable than @@version or + * serverproperty('edition'). + * Reference: http://msdn.microsoft.com/en-us/library/ee336261.aspx * - * @return + * SERVERPROPERTY('EngineEdition') means + * Database Engine edition of the instance of SQL Server installed on the server. + * 1 = Personal or Desktop Engine (Not available for SQL Server.) + * 2 = Standard (This is returned for Standard and Workgroup.) + * 3 = Enterprise (This is returned for Enterprise, Enterprise Evaluation, and Developer.) + * 4 = Express (This is returned for Express, Express with Advanced Services, and Windows Embedded SQL.) + * 5 = SQL Azure + * 6 = SQL Azure DW + * 8 = Managed Instance + * Base data type: int */ - public static String getServerType() { - String serverType = null; - - String serverTypeProperty = getConfiguredProperty("server.type"); - if (null == serverTypeProperty) { - // default to SQL Server - serverType = SERVER_TYPE_SQL_SERVER; - } else if (serverTypeProperty.equalsIgnoreCase(SERVER_TYPE_SQL_AZURE)) { - serverType = SERVER_TYPE_SQL_AZURE; - } else if (serverTypeProperty.equalsIgnoreCase(SERVER_TYPE_SQL_SERVER)) { - serverType = SERVER_TYPE_SQL_SERVER; - } else { - if (log.isLoggable(Level.FINE)) { - log.fine("Server.type '" + serverTypeProperty + "' is not supported yet. Default to SQL Server"); + public static boolean isAzure(Connection con) { + if (null == isAzure) { + try (Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT CAST(SERVERPROPERTY('EngineEdition') as INT)")) { + rs.next(); + + int engineEdition = rs.getInt(1); + isAzure = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE || engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_DW || engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_MI); + isAzureDW = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_DW); + isAzureMI = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_MI); + + } catch (SQLException e) { + isAzure = false; + isAzureDW = false; + isAzureMI = false; } - serverType = SERVER_TYPE_SQL_SERVER; + return isAzure; + } else { + return isAzure; } - return serverType; } + public static boolean isAzureDW(Connection con) { + isAzure(con); + return isAzureDW; + } + + public static boolean isAzureMI(Connection con) { + isAzure(con); + return isAzureMI; + } /** * Read variable from property files if found null try to read from env. * @@ -130,7 +155,7 @@ public static String getConfiguredProperty(String key, String defaultValue) { * @param javatype * @return */ - public static SqlType find(Class javatype) { + public static SqlType find(Class javatype) { if (null != types) { types(); for (SqlType type : types) { @@ -288,6 +313,13 @@ public static void dropDatabaseIfExists(String databaseName, java.sql.Statement + escapeSingleQuotes(databaseName) + "') DROP DATABASE [" + databaseName + "]"); } + public static void dropTriggerIfExists(String triggerName, java.sql.Statement stmt) throws SQLException { + stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" + + " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n" + + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + + Constants.SEMI_COLON); + } + /** * actually perform the "DROP TABLE / PROCEDURE" */ @@ -347,14 +379,12 @@ public static boolean serverSupportsUTF8(Connection connection) throws SQLExcept * length of the array * @return */ - final static char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; - public static String bytesToHexString(byte[] b, int length) { StringBuilder sb = new StringBuilder(length * 2); for (int i = 0; i < length; i++) { int hexVal = b[i] & 0xFF; - sb.append(hexChars[(hexVal & 0xF0) >> 4]); - sb.append(hexChars[(hexVal & 0x0F)]); + sb.append(HEXCHARS[(hexVal & 0xF0) >> 4]); + sb.append(HEXCHARS[(hexVal & 0x0F)]); } return sb.toString(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/TimeoutTest.java index 9defca488..74cbf0912 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TimeoutTest.java @@ -10,9 +10,9 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -23,6 +23,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -31,6 +32,7 @@ @RunWith(JUnitPlatform.class) +@Tag("AzureDWTest") public class TimeoutTest extends AbstractTest { private static final int TIMEOUT_SECONDS = 2; private static final String WAIT_FOR_ONE_MINUTE_SQL = "WAITFOR DELAY '00:01:00'"; @@ -56,6 +58,7 @@ public void after() throws InterruptedException { @Test public void testBasicQueryTimeout() { + assumeTrue(!isSqlAzureDW(), TestResource.getResource("R_issueAzureDW")); assertThrows(SQLTimeoutException.class, () -> { runQuery(WAIT_FOR_ONE_MINUTE_SQL, TIMEOUT_SECONDS); }); @@ -63,6 +66,7 @@ public void testBasicQueryTimeout() { @Test public void testQueryTimeoutValid() { + assumeTrue(!isSqlAzureDW(), TestResource.getResource("R_issueAzureDW")); long start = System.currentTimeMillis(); assertThrows(SQLTimeoutException.class, () -> { runQuery(WAIT_FOR_ONE_MINUTE_SQL, TIMEOUT_SECONDS); @@ -126,10 +130,6 @@ public void testNestedTimeoutShouldKeepTimerThreadRunning() throws SQLException } } - private static Connection getConnection() throws SQLException { - return DriverManager.getConnection(connectionString); - } - private static void runQuery(String query, int timeout) throws SQLException { try (Connection conn = getConnection()) { runQuery(conn, query, timeout); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/UtilTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/UtilTest.java index 13c76c0f9..2caaf0b45 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/UtilTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/UtilTest.java @@ -9,6 +9,7 @@ import java.sql.SQLException; import java.util.UUID; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -19,6 +20,7 @@ * */ @RunWith(JUnitPlatform.class) +@Tag("AzureDWTest") public class UtilTest { @Test diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypesTest.java index c08bab590..4aa221785 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypesTest.java @@ -5,7 +5,6 @@ package com.microsoft.sqlserver.jdbc.bulkCopy; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -21,6 +20,7 @@ import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -53,7 +53,7 @@ private void testBulkCopyResultSet(boolean setSelectMethod, Integer resultSetTyp Integer resultSetConcurrency) throws SQLException { setupVariation(); - try (Connection connnection = DriverManager + try (Connection connnection = PrepUtil .getConnection(connectionString + (setSelectMethod ? ";selectMethod=cursor;" : "")); Statement statement = (null != resultSetType || null != resultSetConcurrency) ? connnection .createStatement(resultSetType, resultSetConcurrency) : connnection.createStatement(); @@ -85,7 +85,7 @@ private void setupVariation() throws SQLException { } private void terminateVariation() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); TestUtils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java index 47a5209da..6fba3512a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java @@ -30,6 +30,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBStatement; @@ -191,7 +192,7 @@ static void validateValuesFromCSV(DBTable destinationTable, String inputFile) { br.readLine(); // skip first line as it is header try (DBResultSet dstResultSet = stmt - .executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + .executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + Constants.SEMI_COLON)) { ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); int totalColumns = destMeta.getColumnCount(); while (dstResultSet.next()) { 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 b9de55440..0802e70d6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -21,6 +21,7 @@ import com.microsoft.sqlserver.jdbc.ComparisonUtil; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBStatement; @@ -47,9 +48,9 @@ public void testNoExplicitCM() throws SQLException { // set up bulkCopy without explicit column mapping BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable); } finally { TestUtils.dropTableIfExists(destTable.getEscapedTableName(), (Statement) stmt.product()); @@ -69,9 +70,9 @@ public void testExplicitCM() throws SQLException { // set up bulkCopy with explicit column mapping BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); for (int i = 1; i <= destTable.totalColumns(); i++) { int select = i % 4; switch (select) { @@ -114,9 +115,9 @@ public void testUnicodeCM() throws SQLException { // set up bulkCopy with explicit column mapping BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); for (int i = 1; i <= destTableUnicode.totalColumns(); i++) { int select = i % 4; switch (select) { @@ -165,9 +166,9 @@ public void testRepetitiveCM() throws SQLException { // set up bulkCopy with explicit column mapping BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); for (int i = 1; i <= sourceTable1.totalColumns(); i++) { int select = i % 4; switch (select) { @@ -219,9 +220,9 @@ public void testImplicitMismatchCM() throws SQLException { // set up bulkCopy with explicit column mapping BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); for (int i = 1; i <= destTable.totalColumns(); i++) { int select = i % 4; switch (select) { @@ -259,9 +260,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy with wrong column names BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping("wrongFirst", "wrongSecond"); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); @@ -271,9 +272,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy with invalid ordinal, column no 65 does not exist bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping(sourceTable.getColumnName(1), 65); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); @@ -283,9 +284,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy with invalid ordinal, column no 42 does not exist bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping(42, destTable.getColumnName(1)); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); @@ -295,9 +296,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy with invalid ordinal, column no 42 and 65 do not exist bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping(42, 65); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); @@ -307,9 +308,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy while passing empty string as column mapping bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping(sourceTable.getColumnName(1), " "); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); @@ -319,9 +320,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy with 0 ordinal column mapping bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping(0, 0); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); @@ -331,9 +332,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy with negative ordinal column mapping bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping(-3, -6); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); @@ -343,9 +344,9 @@ public void testInvalidCM() throws SQLException { // set up bulkCopy with Integer.MIN_VALUE and Integer.MAX_VALUE column mapping bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); bulkWrapper.setColumnMapping(Integer.MIN_VALUE, Integer.MAX_VALUE); BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, destTable, true, true); } finally { @@ -367,9 +368,9 @@ private void validateValuesRepetitiveCM(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { try (DBStatement srcStmt = con.createStatement(); DBStatement dstStmt = con.createStatement(); DBResultSet srcResultSet = srcStmt - .executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - DBResultSet dstResultSet = dstStmt - .executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + .executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + Constants.SEMI_COLON); + DBResultSet dstResultSet = dstStmt.executeQuery( + "SELECT * FROM " + destinationTable.getEscapedTableName() + Constants.SEMI_COLON)) { ResultSetMetaData sourceMeta = ((ResultSet) srcResultSet.product()).getMetaData(); int totalColumns = sourceMeta.getColumnCount(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java index 758fce3eb..b4b485d14 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java @@ -25,6 +25,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopyOptions; import com.microsoft.sqlserver.jdbc.SQLServerConnection; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -152,9 +153,9 @@ public void execute() throws SQLException { @DisplayName("BulkCopy:test null SQLServerBulkCopyOptions") public void testEmptyBulkCopyOptions() { BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); SQLServerBulkCopyOptions option = null; bulkWrapper.useBulkCopyOptions(true); bulkWrapper.setBulkOptions(option); @@ -219,9 +220,9 @@ private List createTestDatatestBulkCopyOption() { BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); bulkWrapper.testName = testCaseName; - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); if (!(method.getName()).equalsIgnoreCase("setUseInternalTransaction") @@ -229,7 +230,7 @@ private List createTestDatatestBulkCopyOption() { method.invoke(option, true); bulkWrapper.useBulkCopyOptions(true); bulkWrapper.setBulkOptions(option); - bulkWrapper.testName += method.getName() + ";"; + bulkWrapper.testName += method.getName() + Constants.SEMI_COLON; testData.add(bulkWrapper); } } catch (Exception ex) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java index e6812475a..1741c9c73 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java @@ -21,6 +21,7 @@ import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; @@ -43,9 +44,9 @@ public void testISQLServerBulkRecord() throws SQLException { BulkData Bdata = new BulkData(dstTable); BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); BulkCopyTestUtil.performBulkCopy(bulkWrapper, Bdata, dstTable); } finally { if (null != dstTable) { @@ -104,7 +105,7 @@ private class ColumnMetadata { for (int j = 0; j < totalColumn; j++) { SqlType sqlType = dstTable.getSqlType(j); if (JDBCType.BIT == sqlType.getJdbctype()) { - CurrentRow[j] = ((0 == random.nextInt(2)) ? Boolean.FALSE : Boolean.TRUE); + CurrentRow[j] = ((0 == Constants.RANDOM.nextInt(2)) ? Boolean.FALSE : Boolean.TRUE); } else { if (j == 0) { CurrentRow[j] = i + 1; 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 e7a6b00de..1b6c18a24 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -8,7 +8,6 @@ import java.math.BigDecimal; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -28,6 +27,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -62,7 +62,7 @@ public void testServerCursors() throws SQLException { } private void serverCursorsTest(int resultSetType, int resultSetConcurrency) throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { dropTables(stmt); createTables(stmt); @@ -90,7 +90,7 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro public void testSelectMethodSetToCursor() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - try (Connection conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = PrepUtil.getConnection(connectionString, info); Statement stmt = conn.createStatement()) { dropTables(stmt); createTables(stmt); @@ -115,7 +115,7 @@ public void testSelectMethodSetToCursor() throws SQLException { */ @Test public void testMultiplePreparedStatementAndResultSet() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { dropTables(stmt); createTables(stmt); @@ -170,9 +170,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 " + AbstractSQLGenerator.escapeIdentifier(desTable) + " ORDER BY id ASC")) { + try (Connection conn = getConnection(); ResultSet rs = conn.createStatement().executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(desTable) + " ORDER BY id ASC")) { int expectedArrayLength = expectedBigDecimals.length; @@ -197,7 +196,7 @@ private static void populateSourceTable() throws SQLException { String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { for (int i = 0; i < expectedBigDecimals.length; i++) { pstmt.setBigDecimal(1, expectedBigDecimals[i]); @@ -234,7 +233,7 @@ private static void createTables(Statement stmt) throws SQLException { */ @AfterAll public static void terminate() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { dropTables(stmt); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyRowSetTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyRowSetTest.java new file mode 100644 index 000000000..d8ee803dd --- /dev/null +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyRowSetTest.java @@ -0,0 +1,83 @@ +package com.microsoft.sqlserver.jdbc.bulkCopy; + +import static org.junit.Assert.assertEquals; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import javax.sql.RowSetMetaData; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetFactory; +import javax.sql.rowset.RowSetMetaDataImpl; +import javax.sql.rowset.RowSetProvider; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.opentest4j.TestAbortedException; + +import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; +import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; +import com.microsoft.sqlserver.testframework.AbstractTest; + +public class BulkCopyRowSetTest extends AbstractTest { + + private static String tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("BulkCopyFloatTest")); + + @Test + public void testBulkCopyFloatRowSet() throws SQLException { + try (Connection con = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + RowSetFactory rsf = RowSetProvider.newFactory(); + CachedRowSet crs = rsf.createCachedRowSet(); + RowSetMetaData rsmd = new RowSetMetaDataImpl(); + rsmd.setColumnCount(2); + rsmd.setColumnName(1, "c1"); + rsmd.setColumnName(2, "c2"); + rsmd.setColumnType(1, java.sql.Types.FLOAT); + rsmd.setColumnType(2, java.sql.Types.FLOAT); + + Float floatData = RandomData.generateReal(false); + + crs.setMetaData(rsmd); + crs.moveToInsertRow(); + crs.updateFloat(1, floatData); + crs.updateFloat(2, floatData); + crs.insertRow(); + crs.moveToCurrentRow(); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(con)) { + bcOperation.setDestinationTableName(tableName); + bcOperation.writeToServer(crs); + } + + ResultSet rs = stmt.executeQuery("select * from " + tableName); + rs.next(); + assertEquals(floatData, (Float) rs.getFloat(1)); + assertEquals(floatData, (Float) rs.getFloat(2)); + } + } + + @BeforeAll + public static void testSetup() throws TestAbortedException, Exception { + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + String sql1 = "create table " + tableName + " (c1 float, c2 real)"; + stmt.execute(sql1); + } + } + + @AfterAll + public static void terminateVariation() throws SQLException { + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(tableName, stmt); + } + } +} diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java index 72889b7ab..2c716eeed 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java @@ -14,6 +14,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopyOptions; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -57,9 +58,9 @@ public void execute() throws SQLException { private void testBulkCopyWithTimeout(int timeout) throws SQLException { BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == random.nextInt(2)) ? true : false, ds); - bulkWrapper.setUsingXAConnection((0 == random.nextInt(2)) ? true : false, dsXA); - bulkWrapper.setUsingPooledConnection((0 == random.nextInt(2)) ? true : false, dsPool); + bulkWrapper.setUsingConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, ds); + bulkWrapper.setUsingXAConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsXA); + bulkWrapper.setUsingPooledConnection((0 == Constants.RANDOM.nextInt(2)) ? true : false, dsPool); SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); option.setBulkCopyTimeout(timeout); bulkWrapper.useBulkCopyOptions(true); 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 2ee2f9358..3a6f89002 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java @@ -10,7 +10,6 @@ import java.io.IOException; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -41,7 +40,6 @@ @RunWith(JUnitPlatform.class) public class ISQLServerBulkRecordIssuesTest extends AbstractTest { - // static Statement stmt = null; static String query; static String srcTable = RandomUtil.getIdentifier("sourceTable"); static String destTable = RandomUtil.getIdentifier("destTable"); @@ -58,7 +56,7 @@ public void testVarchar() throws Exception { variation = "testVarchar"; BulkData bData = new BulkData(variation); query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA varchar(2))"; - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate(query); try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { @@ -69,7 +67,7 @@ public void testVarchar() throws Exception { } catch (Exception e) { if (e instanceof SQLException) { assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); + TestResource.getResource("R_invalidErrorMessage") + e.getMessage()); } else { fail(e.getMessage()); } @@ -88,7 +86,7 @@ public void testSmalldatetime() throws Exception { BulkData bData = new BulkData(variation); String value = ("1954-05-22 02:44:00.0").toString(); query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA smalldatetime)"; - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate(query); try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { @@ -116,7 +114,7 @@ public void testSmalldatetimeOutofRange() throws Exception { BulkData bData = new BulkData(variation); query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA smalldatetime)"; - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate(query); try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { @@ -129,7 +127,7 @@ public void testSmalldatetimeOutofRange() throws Exception { Object[] msgArgs = {"character string", "smalldatetime"}; assertTrue(e.getMessage().contains(form.format(msgArgs)), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); + TestResource.getResource("R_invalidErrorMessage") + e.getMessage()); } else { fail(e.getMessage()); } @@ -147,7 +145,7 @@ public void testBinaryColumnAsByte() throws Exception { variation = "testBinaryColumnAsByte"; BulkData bData = new BulkData(variation); query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate(query); try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { @@ -157,7 +155,7 @@ public void testBinaryColumnAsByte() throws Exception { } catch (Exception e) { if (e instanceof SQLException) { assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); + TestResource.getResource("R_invalidErrorMessage") + e.getMessage()); } else { fail(e.getMessage()); } @@ -175,7 +173,7 @@ public void testBinaryColumnAsString() throws Exception { variation = "testBinaryColumnAsString"; BulkData bData = new BulkData(variation); query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate(query); try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { @@ -185,7 +183,7 @@ public void testBinaryColumnAsString() throws Exception { } catch (Exception e) { if (e instanceof SQLException) { assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); + TestResource.getResource("R_invalidErrorMessage") + e.getMessage()); } else { fail(e.getMessage()); } @@ -203,7 +201,7 @@ public void testSendValidValueforBinaryColumnAsString() throws Exception { variation = "testSendValidValueforBinaryColumnAsString"; BulkData bData = new BulkData(variation); query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate(query); try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { @@ -231,7 +229,7 @@ public void testSendValidValueforBinaryColumnAsString() throws Exception { */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); } @@ -244,7 +242,7 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterEach public void afterEachTests() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); 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 0ce9a723a..3825ec542 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/BvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/BvtTest.java @@ -326,7 +326,7 @@ public void testResultSetAndClose() throws SQLException { if (null != rs) rs.close(); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableMixedTest.java index 07890734c..d93fe8cc6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableMixedTest.java @@ -5,7 +5,6 @@ import java.sql.CallableStatement; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -30,20 +29,18 @@ public void datatypestest() throws Exception { String procName = RandomUtil.getIdentifier("SPFOO3"); String escapedProcName = AbstractSQLGenerator.escapeIdentifier(procName); - try (Connection conn = DriverManager.getConnection(connectionString)) { - try (Statement stmt = conn.createStatement()) { - TestUtils.dropTableIfExists(escapedTableName, stmt); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { + TestUtils.dropTableIfExists(escapedTableName, stmt); - String createSQL = "create table " + escapedTableName + "(c1_int int primary key, col2 int)"; - stmt.executeUpdate(createSQL); + String createSQL = "create table " + escapedTableName + "(c1_int int primary key, col2 int)"; + stmt.executeUpdate(createSQL); - stmt.executeUpdate("Insert into " + escapedTableName + " values(0, 1)"); + stmt.executeUpdate("Insert into " + escapedTableName + " values(0, 1)"); - stmt.executeUpdate("CREATE PROCEDURE " + escapedProcName - + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " - + escapedTableName - + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - } + stmt.executeUpdate("CREATE PROCEDURE " + escapedProcName + + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " + + escapedTableName + + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); try (CallableStatement cstmt = conn.prepareCall("{ ? = CALL " + escapedProcName + " (?, ?, ?, ?) }")) { cstmt.registerOutParameter((int) 1, (int) 4); @@ -75,11 +72,10 @@ public void datatypestest() throws Exception { } } } finally { - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(escapedTableName, stmt); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } 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 4cac1a8e4..33a87dd74 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -5,7 +5,6 @@ import java.sql.CallableStatement; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -26,6 +25,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -46,8 +46,7 @@ public class CallableStatementTest extends AbstractTest { @BeforeAll public static void setupTest() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameGUID), stmt); TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID), stmt); TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(setNullProcedureName), stmt); @@ -173,9 +172,7 @@ public void inputParamsTest() throws SQLException { */ @AfterAll public static void cleanup() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { - + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameGUID), stmt); TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID), stmt); TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(setNullProcedureName), stmt); @@ -186,7 +183,7 @@ public static void cleanup() throws SQLException { private static void createGUIDStoredProcedure(Statement stmt) throws SQLException { String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID) + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " - + AbstractSQLGenerator.escapeIdentifier(tableNameGUID) + ";"; + + AbstractSQLGenerator.escapeIdentifier(tableNameGUID) + Constants.SEMI_COLON; 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 bcf84bc29..5d749ba78 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -10,7 +10,6 @@ import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.ResultSet; import java.sql.SQLException; @@ -42,6 +41,8 @@ import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -53,45 +54,6 @@ public class ConnectionDriverTest extends AbstractTest { String randomServer = RandomUtil.getIdentifier("Server"); - /** - * test connection properties - * - * @throws SQLException - */ - @Test - public void testConnectionDriver() throws SQLException { - SQLServerDriver d = new SQLServerDriver(); - Properties info = new Properties(); - StringBuffer url = new StringBuffer(); - url.append("jdbc:sqlserver://" + randomServer + ";packetSize=512;"); - // test defaults - DriverPropertyInfo[] infoArray = d.getPropertyInfo(url.toString(), info); - for (DriverPropertyInfo anInfoArray1 : infoArray) { - logger.fine(anInfoArray1.name); - logger.fine(anInfoArray1.description); - logger.fine(Boolean.valueOf(anInfoArray1.required).toString()); - logger.fine(anInfoArray1.value); - } - - url.append("encrypt=true; trustStore=someStore; trustStorePassword=somepassword;"); - url.append("hostNameInCertificate=someHost; trustServerCertificate=true"); - infoArray = d.getPropertyInfo(url.toString(), info); - for (DriverPropertyInfo anInfoArray : infoArray) { - if (anInfoArray.name.equals("encrypt")) { - assertTrue(anInfoArray.value.equals("true"), TestResource.getResource("R_valuesAreDifferent")); - } - if (anInfoArray.name.equals("trustStore")) { - assertTrue(anInfoArray.value.equals("someStore"), TestResource.getResource("R_valuesAreDifferent")); - } - if (anInfoArray.name.equals("trustStorePassword")) { - assertTrue(anInfoArray.value.equals("somepassword"), TestResource.getResource("R_valuesAreDifferent")); - } - if (anInfoArray.name.equals("hostNameInCertificate")) { - assertTrue(anInfoArray.value.equals("someHost"), TestResource.getResource("R_valuesAreDifferent")); - } - } - } - /** * test connection properties with SQLServerDataSource */ @@ -126,19 +88,11 @@ public void testEncryptedConnection() throws SQLException { try (Connection con = ds.getConnection()) {} } - @Test - public void testJdbcDriverMethod() throws SQLFeatureNotSupportedException { - SQLServerDriver serverDriver = new SQLServerDriver(); - Logger logger = serverDriver.getParentLogger(); - assertEquals(logger.getName(), "com.microsoft.sqlserver.jdbc", - TestResource.getResource("R_parrentLoggerNameWrong")); - } - @Test public void testJdbcDataSourceMethod() throws SQLFeatureNotSupportedException { SQLServerDataSource fxds = new SQLServerDataSource(); Logger logger = fxds.getParentLogger(); - assertEquals(logger.getName(), "com.microsoft.sqlserver.jdbc", + assertEquals(logger.getName(), Constants.MSSQL_JDBC_PACKAGE, TestResource.getResource("R_parrentLoggerNameWrong")); } @@ -247,14 +201,13 @@ public void testConnectionClosed() throws SQLException { // check to make sure that connection is closed. assertTrue(con.isClosed(), TestResource.getResource("R_connectionIsNotClosed")); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @Test public void testIsWrapperFor() throws SQLException, ClassNotFoundException { - try (Connection conn = DriverManager.getConnection(connectionString); - SQLServerConnection ssconn = (SQLServerConnection) conn) { + try (Connection conn = getConnection(); SQLServerConnection ssconn = (SQLServerConnection) conn) { boolean isWrapper; isWrapper = ssconn.isWrapperFor(ssconn.getClass()); MessageFormat form = new MessageFormat(TestResource.getResource("R_supportUnwrapping")); @@ -264,10 +217,11 @@ public void testIsWrapperFor() throws SQLException, ClassNotFoundException { assertEquals(ISQLServerConnection.TRANSACTION_SNAPSHOT, ISQLServerConnection.TRANSACTION_SNAPSHOT, TestResource.getResource("R_cantAccessSnapshot")); - isWrapper = ssconn.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + isWrapper = ssconn.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerConnection")); Object[] msgArgs2 = {"ISQLServerConnection"}; assertTrue(isWrapper, form.format(msgArgs2)); - ssconn.unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + + ssconn.unwrap(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerConnection")); assertEquals(ISQLServerConnection.TRANSACTION_SNAPSHOT, ISQLServerConnection.TRANSACTION_SNAPSHOT, TestResource.getResource("R_cantAccessSnapshot")); @@ -277,14 +231,14 @@ public void testIsWrapperFor() throws SQLException, ClassNotFoundException { @Test public void testNewConnection() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { assertTrue(conn.isValid(0), TestResource.getResource("R_newConnectionShouldBeValid")); } } @Test public void testClosedConnection() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { conn.close(); assertTrue(!conn.isValid(0), TestResource.getResource("R_closedConnectionShouldBeInvalid")); } @@ -292,7 +246,7 @@ public void testClosedConnection() throws SQLException { @Test public void testNegativeTimeout() throws Exception { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { try { conn.isValid(-42); throw new Exception(TestResource.getResource("R_noExceptionNegativeTimeout")); @@ -310,8 +264,7 @@ public void testDeadConnection() throws SQLException { assumeFalse(isSqlAzure(), TestResource.getResource("R_skipAzure")); String tableName = RandomUtil.getIdentifier("ConnectionTestTable"); - try (SQLServerConnection conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";responseBuffering=adaptive"); + try (Connection conn = PrepUtil.getConnection(connectionString + ";responseBuffering=adaptive"); Statement stmt = conn.createStatement()) { conn.setAutoCommit(false); @@ -333,10 +286,10 @@ public void testDeadConnection() throws SQLException { } assertEquals(conn.isValid(5), false, TestResource.getResource("R_deadConnection")); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } finally { if (null != tableName) { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil .getConnection(connectionString + ";responseBuffering=adaptive"); Statement stmt = conn.createStatement()) { stmt.execute("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); @@ -347,7 +300,7 @@ public void testDeadConnection() throws SQLException { @Test public void testClientConnectionId() throws Exception { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (ISQLServerConnection conn = (ISQLServerConnection) getConnection()) { assertTrue(conn.getClientConnectionId() != null, TestResource.getResource("R_clientConnectionIdNull")); conn.close(); try { @@ -361,8 +314,8 @@ public void testClientConnectionId() throws Exception { } // Wrong database, ClientConnectionId should be available in error message - try (SQLServerConnection conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";databaseName=" + RandomUtil.getIdentifierForDB("DataBase") + ";")) { + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil.getConnection(connectionString + ";databaseName=" + + RandomUtil.getIdentifierForDB("DataBase") + Constants.SEMI_COLON)) { conn.close(); } catch (SQLException e) { @@ -371,7 +324,7 @@ public void testClientConnectionId() throws Exception { } // Nonexist host, ClientConnectionId should not be available in error message - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection( + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil.getConnection( connectionString + ";instanceName=" + RandomUtil.getIdentifier("Instance") + ";logintimeout=5;")) { conn.close(); @@ -506,7 +459,7 @@ public void testIncorrectDatabaseWithFailoverPartner() throws SQLException { @Test public void testAbortBadParam() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { try { conn.abort(null); } catch (SQLException e) { @@ -517,22 +470,23 @@ public void testAbortBadParam() throws SQLException { @Test public void testAbort() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { Executor executor = Executors.newFixedThreadPool(2); conn.abort(executor); + assert (conn.isClosed()); } } @Test public void testSetSchema() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { conn.setSchema(RandomUtil.getIdentifier("schema")); } } @Test public void testGetSchema() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { conn.getSchema(); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionWrapper43Test.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionWrapper43Test.java index 8f8825b71..9f2e0fd89 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionWrapper43Test.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionWrapper43Test.java @@ -8,7 +8,6 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; -import java.sql.DriverManager; import java.sql.SQLException; import org.junit.jupiter.api.AfterAll; @@ -57,7 +56,7 @@ public void SQLServerConnection43Test() throws SQLException { @BeforeAll public static void setupConnection() throws SQLException { - connection = DriverManager.getConnection(connectionString); + connection = getConnection(); DatabaseMetaData metadata = connection.getMetaData(); major = metadata.getJDBCMajorVersion(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java index 3d5d799f7..646dbd602 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java @@ -28,6 +28,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerXADataSource; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; @RunWith(JUnitPlatform.class) @@ -67,7 +68,7 @@ public void testDSNormal() throws ClassNotFoundException, IOException, SQLExcept @Test public void testDSTSPassword() throws ClassNotFoundException, IOException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); - System.setProperty("java.net.preferIPv6Addresses", "true"); + System.setProperty("java.net.preferIPv6Addresses", Boolean.TRUE.toString()); ds.setURL(connectionString); ds.setTrustStorePassword("wrong_password"); try (Connection conn = ds.getConnection()) {} @@ -81,32 +82,32 @@ public void testDSTSPassword() throws ClassNotFoundException, IOException, SQLEx @Tag("AzureDWTest") public void testInterfaceWrapping() throws ClassNotFoundException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); - assertEquals(true, ds.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerDataSource"))); - assertEquals(true, ds.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDataSource"))); + assertEquals(true, ds.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerDataSource"))); + assertEquals(true, ds.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerDataSource"))); assertEquals(true, ds.isWrapperFor(Class.forName("javax.sql.CommonDataSource"))); ISQLServerDataSource ids = (ISQLServerDataSource) (ds - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerDataSource"))); + .unwrap(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerDataSource"))); ids.setApplicationName("AppName"); SQLServerConnectionPoolDataSource poolDS = new SQLServerConnectionPoolDataSource(); - assertEquals(true, poolDS.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerDataSource"))); - assertEquals(true, poolDS.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDataSource"))); - assertEquals(true, - poolDS.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource"))); + assertEquals(true, poolDS.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerDataSource"))); + assertEquals(true, poolDS.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerDataSource"))); + assertEquals(true, poolDS + .isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerConnectionPoolDataSource"))); assertEquals(true, poolDS.isWrapperFor(Class.forName("javax.sql.CommonDataSource"))); ISQLServerDataSource ids2 = (ISQLServerDataSource) (poolDS - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerDataSource"))); + .unwrap(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerDataSource"))); ids2.setApplicationName("AppName"); SQLServerXADataSource xaDS = new SQLServerXADataSource(); - assertEquals(true, xaDS.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerDataSource"))); - assertEquals(true, xaDS.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDataSource"))); + assertEquals(true, xaDS.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerDataSource"))); + assertEquals(true, xaDS.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerDataSource"))); assertEquals(true, - xaDS.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource"))); - assertEquals(true, xaDS.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerXADataSource"))); + xaDS.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerConnectionPoolDataSource"))); + assertEquals(true, xaDS.isWrapperFor(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerXADataSource"))); assertEquals(true, xaDS.isWrapperFor(Class.forName("javax.sql.CommonDataSource"))); ISQLServerDataSource ids3 = (ISQLServerDataSource) (xaDS - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerDataSource"))); + .unwrap(Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".ISQLServerDataSource"))); ids3.setApplicationName("AppName"); } 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 401cc459a..03eeb5c83 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -9,10 +9,7 @@ import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -120,7 +117,7 @@ public void testConnectionPoolConnFunctions() throws SQLException { con.clearWarnings(); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } finally { if (null != pc) { pc.close(); @@ -140,7 +137,7 @@ public void testConnectionPoolClose() throws SQLException { // assert that the first connection is closed. assertTrue(con.isClosed(), TestResource.getResource("R_connectionNotClosedWithPoolClose")); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } finally { if (null != pc) { pc.close(); @@ -232,28 +229,6 @@ private static void connect(DataSource ds) throws SQLException { } } - /** - * count number of mssql-jdbc-TimeoutTimer threads - * - * @return - */ - private static int countTimeoutThreads() { - int count = 0; - String threadName = "mssql-jdbc-TimeoutTimer"; - - ThreadInfo[] tinfos = ManagementFactory.getThreadMXBean() - .getThreadInfo(ManagementFactory.getThreadMXBean().getAllThreadIds(), 0); - - for (ThreadInfo ti : tinfos) { - if ((ti.getThreadName().startsWith(threadName)) - && (ti.getThreadState().equals(java.lang.Thread.State.TIMED_WAITING))) { - count++; - } - } - - return count; - } - /** * drop the tables * @@ -261,7 +236,7 @@ private static int countTimeoutThreads() { */ @AfterAll public static void afterAll() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); 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 fa402a7d2..46a65d587 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -30,7 +30,6 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.PrepUtil; /** @@ -74,7 +73,7 @@ public void testModifiableConnectionProperties() throws SQLException { String sCatalog2 = RandomUtil.getIdentifier("RequestBoundaryDatabase"); boolean useBulkCopyForBatchInsert2 = false; - try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { + try (SQLServerConnection con = getConnection(); Statement stmt = con.createStatement()) { if (TestUtils.isJDBC43OrGreater(con)) { // Second database stmt.executeUpdate("CREATE DATABASE [" + sCatalog2 + "]"); @@ -134,7 +133,7 @@ public void testModifiableConnectionProperties() throws SQLException { con.setCatalog("master"); } } finally { - try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { + try (SQLServerConnection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropDatabaseIfExists(sCatalog2, stmt); } } @@ -147,7 +146,7 @@ public void testModifiableConnectionProperties() throws SQLException { */ @Test public void testWarnings() throws SQLException { - try (SQLServerConnection con = connect()) { + try (SQLServerConnection con = getConnection()) { if (TestUtils.isJDBC43OrGreater(con)) { con.beginRequest(); generateWarning(con); @@ -176,7 +175,7 @@ public void testWarnings() throws SQLException { */ @Test public void testOpenTransactions() throws SQLException { - try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { + try (SQLServerConnection con = getConnection(); Statement stmt = con.createStatement()) { if (TestUtils.isJDBC43OrGreater(con)) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col int)"); @@ -206,10 +205,9 @@ public void testOpenTransactions() throws SQLException { * * @throws SQLException */ - @SuppressWarnings("resource") @Test public void testStatements() throws SQLException { - try (SQLServerConnection con = connect();) { + try (SQLServerConnection con = getConnection();) { if (TestUtils.isJDBC43OrGreater(con)) { try (Statement stmt1 = con.createStatement()) { con.beginRequest(); @@ -285,7 +283,7 @@ class Variables { final Variables sharedVariables = new Variables(); final CountDownLatch latch = new CountDownLatch(3); try { - sharedVariables.con = connect(); + sharedVariables.con = getConnection(); if (TestUtils.isJDBC43OrGreater(sharedVariables.con)) { Thread thread1 = new Thread() { public void run() { @@ -383,16 +381,6 @@ public void testNewMethods() { } } - private SQLServerConnection connect() throws SQLException { - SQLServerConnection connection = null; - try { - connection = PrepUtil.getConnection(connectionString); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - return connection; - } - private void setConnectionFields(SQLServerConnection con, boolean autoCommitMode, int transactionIsolationLevel, int networkTimeout, int holdability, boolean sendTimeAsDatetime, int statementPoolingCacheSize, boolean disableStatementPooling, int serverPreparedStatementDiscardThreshold, diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java index 79d8c28d2..6962a171f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java @@ -10,7 +10,6 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; -import java.sql.DriverManager; import java.text.MessageFormat; import org.junit.jupiter.api.Tag; @@ -22,6 +21,7 @@ import com.microsoft.sqlserver.jdbc.StringUtils; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.PrepUtil; /** @@ -39,7 +39,7 @@ public class SSLProtocolTest extends AbstractTest { */ public void testWithSupportedProtocols(String sslProtocol) throws Exception { String url = connectionString + ";sslProtocol=" + sslProtocol; - try (Connection con = DriverManager.getConnection(url)) { + try (Connection con = PrepUtil.getConnection(url)) { DatabaseMetaData dbmd = con.getMetaData(); assertNotNull(dbmd); assertTrue(!StringUtils.isEmpty(dbmd.getDatabaseProductName())); @@ -59,7 +59,7 @@ public void testWithSupportedProtocols(String sslProtocol) throws Exception { */ public void testWithUnSupportedProtocols(String sslProtocol) throws Exception { String url = connectionString + ";sslProtocol=" + sslProtocol; - try (Connection con = DriverManager.getConnection(url)) { + try (Connection con = PrepUtil.getConnection(url)) { assertFalse(true, TestResource.getResource("R_protocolVersion")); } catch (SQLServerException e) { assertTrue(true, TestResource.getResource("R_shouldThrowException")); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java index 61a17bea6..7e8ecc45f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java @@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; @@ -26,6 +25,8 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -42,8 +43,7 @@ public void testDefaultLoginTimeout() { timerStart = System.currentTimeMillis(); // Try a non existing server and see if the default timeout is 15 seconds - try (Connection con = DriverManager - .getConnection("jdbc:sqlserver://" + randomServer + ";user=sa;password=pwd;")) { + try (Connection con = PrepUtil.getConnection("jdbc:sqlserver://" + randomServer + ";user=sa;password=pwd;")) { } catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_tcpipConnectionToHost"))); @@ -63,7 +63,7 @@ public void testFailoverInstanceResolution() throws SQLException { timerStart = System.currentTimeMillis(); // Try a non existing server and see if the default timeout is 15 seconds - try (Connection con = DriverManager + try (Connection con = PrepUtil .getConnection("jdbc:sqlserver://" + randomServer + ";databaseName=FailoverDB_abc;failoverPartner=" + randomServer + "\\foo;user=sa;password=pwd;")) {} catch (Exception e) { assertTrue(e.getMessage().contains(TestResource.getResource("R_tcpipConnectionToHost"))); @@ -81,7 +81,7 @@ public void testFOInstanceResolution2() throws SQLException { long timerEnd = 0; timerStart = System.currentTimeMillis(); - try (Connection con = DriverManager + try (Connection con = PrepUtil .getConnection("jdbc:sqlserver://" + randomServer + "\\fooggg;databaseName=FailoverDB;failoverPartner=" + randomServer + "\\foo;user=sa;password=pwd;")) {} catch (Exception e) { timerEnd = System.currentTimeMillis(); @@ -99,13 +99,13 @@ public void testFOInstanceResolution2() throws SQLException { */ @Test public void testQueryTimeout() throws Exception { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } - try (SQLServerConnection conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";")) { + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil.getConnection( + connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + Constants.SEMI_COLON)) { try (Statement stmt = conn.createStatement()) { stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); @@ -121,10 +121,10 @@ public void testQueryTimeout() throws Exception { try (Statement stmt = conn.createStatement()) { stmt.execute("SELECT @@version"); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -135,21 +135,20 @@ public void testQueryTimeout() throws Exception { */ @Test public void testCancelQueryTimeout() throws Exception { - - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString - + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + ";")) { + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil.getConnection(connectionString + ";queryTimeout=" + + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + Constants.SEMI_COLON)) { - try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + try (Statement stmt = conn.createStatement()) { stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); - throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { - throw e; + fail(TestResource.getResource("R_expectedExceptionNotThrown")); } assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), TestResource.getResource("R_invalidExceptionMessage")); @@ -158,10 +157,10 @@ public void testCancelQueryTimeout() throws Exception { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.execute("SELECT @@version"); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -172,21 +171,22 @@ public void testCancelQueryTimeout() throws Exception { */ @Test public void testCancelQueryTimeoutOnStatement() throws Exception { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";")) { + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil + .getConnection(connectionString + Constants.SEMI_COLON)) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.setQueryTimeout(waitForDelaySeconds / 2); stmt.setCancelQueryTimeout(waitForDelaySeconds); stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); - throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { - throw e; + fail(TestResource.getResource("R_expectedExceptionNotThrown")); } assertEquals(e.getMessage(), TestResource.getResource("R_queryTimedOut"), TestResource.getResource("R_invalidExceptionMessage")); @@ -195,10 +195,10 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.execute("SELECT @@version"); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -209,15 +209,15 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { */ @Test public void testSocketTimeout() throws Exception { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } - try (SQLServerConnection conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";")) { + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil.getConnection( + connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + Constants.SEMI_COLON)) { - try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + try (Statement stmt = conn.createStatement()) { stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { @@ -228,38 +228,38 @@ public void testSocketTimeout() throws Exception { TestResource.getResource("R_invalidExceptionMessage")); } - try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + try (Statement stmt = conn.createStatement()) { stmt.execute("SELECT @@version"); } catch (SQLException e) { assertEquals(e.getMessage(), TestResource.getResource("R_connectionIsClosed"), TestResource.getResource("R_invalidExceptionMessage")); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } - private static void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLException { - try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + private static void dropWaitForDelayProcedure(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } - private void createWaitForDelayPreocedure(SQLServerConnection conn) throws SQLException { - try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + private void createWaitForDelayPreocedure(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { 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()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @AfterAll public static void cleanup() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { dropWaitForDelayProcedure(conn); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java index 8ed2af215..ae296f71a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/WarningTest.java @@ -8,7 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.sql.DriverManager; +import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.Arrays; @@ -20,7 +20,6 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; -import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -30,7 +29,7 @@ public class WarningTest extends AbstractTest { @Test public void testWarnings() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { Properties info = conn.getClientInfo(); conn.setClientInfo(info); @@ -65,7 +64,7 @@ public void testWarnings() throws SQLException { warn = warn.getNextWarning(); assertEquals(null, warn, TestResource.getResource("R_warningsFound")); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } } 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 ffd34ad73..5012813fa 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java @@ -8,9 +8,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.sql.DriverManager; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLTimeoutException; +import java.sql.Statement; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -19,10 +22,6 @@ 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; @@ -46,8 +45,7 @@ public class DatabaseMetaDataForeignKeyTest extends AbstractTest { @BeforeAll public static void setupVariation() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { catalog = conn.getCatalog(); schema = conn.getSchema(); @@ -84,14 +82,13 @@ public static void setupVariation() throws SQLException { + AbstractSQLGenerator.escapeIdentifier(table5) + "(c51) ON DELETE set default ON UPDATE no action," + ")"); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @AfterAll public static void terminateVariation() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); @@ -99,7 +96,7 @@ public static void terminateVariation() throws SQLException { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table4), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table5), stmt); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -111,12 +108,12 @@ public static void terminateVariation() throws SQLException { */ @Test public void testGetImportedKeys() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) conn.getMetaData(); + try (Connection conn = getConnection()) { + DatabaseMetaData dmd = conn.getMetaData(); - try (SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getImportedKeys(null, null, table1); - SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getImportedKeys(catalog, schema, table1); - SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getImportedKeys(catalog, "", table1)) { + try (ResultSet rs1 = dmd.getImportedKeys(null, null, table1); + ResultSet rs2 = dmd.getImportedKeys(catalog, schema, table1); + ResultSet rs3 = dmd.getImportedKeys(catalog, "", table1)) { validateGetImportedKeysResults(rs1); validateGetImportedKeysResults(rs2); @@ -130,11 +127,11 @@ public void testGetImportedKeys() throws SQLException { } } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } - private void validateGetImportedKeysResults(SQLServerResultSet rs) throws SQLException { + private void validateGetImportedKeysResults(ResultSet rs) throws SQLException { int expectedRowCount = 4; int rowCount = 0; @@ -176,15 +173,14 @@ public void testGetExportedKeys() throws SQLException { // expected UPDATE_RULE, expected DELETE_RULE {4, 3}, {2, 0}, {0, 2}, {3, 4}}; - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - - SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) conn.getMetaData(); + try (Connection conn = getConnection()) { + DatabaseMetaData dmd = conn.getMetaData(); for (int i = 0; i < tableNames.length; i++) { String pkTable = tableNames[i]; - try (SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getExportedKeys(null, null, pkTable); - SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getExportedKeys(catalog, schema, pkTable); - SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getExportedKeys(catalog, "", pkTable)) { + try (ResultSet rs1 = dmd.getExportedKeys(null, null, pkTable); + ResultSet rs2 = dmd.getExportedKeys(catalog, schema, pkTable); + ResultSet rs3 = dmd.getExportedKeys(catalog, "", pkTable)) { rs1.next(); assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); @@ -207,7 +203,7 @@ public void testGetExportedKeys() throws SQLException { } } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -225,16 +221,13 @@ public void testGetCrossReference() throws SQLException { // expected UPDATE_RULE, expected DELETE_RULE {4, 3}, {2, 0}, {0, 2}, {3, 4}}; - SQLServerDatabaseMetaData dmd = (SQLServerDatabaseMetaData) connection.getMetaData(); + DatabaseMetaData dmd = connection.getMetaData(); for (int i = 0; i < tableNames.length; i++) { String pkTable = tableNames[i]; - try (SQLServerResultSet rs1 = (SQLServerResultSet) dmd.getCrossReference(null, null, pkTable, null, null, - fkTable); - SQLServerResultSet rs2 = (SQLServerResultSet) dmd.getCrossReference(catalog, schema, pkTable, - catalog, schema, fkTable); - SQLServerResultSet rs3 = (SQLServerResultSet) dmd.getCrossReference(catalog, "", pkTable, catalog, - "", fkTable)) { + try (ResultSet rs1 = dmd.getCrossReference(null, null, pkTable, null, null, fkTable); + ResultSet rs2 = dmd.getCrossReference(catalog, schema, pkTable, catalog, schema, fkTable); + ResultSet rs3 = dmd.getCrossReference(catalog, "", pkTable, catalog, "", fkTable)) { rs1.next(); assertEquals(values[i][0], rs1.getInt("UPDATE_RULE")); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index ca86f0a6e..f7253fe56 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -21,7 +21,6 @@ import java.io.InputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -35,12 +34,12 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; -import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData; import com.microsoft.sqlserver.jdbc.StringUtils; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -57,7 +56,7 @@ public class DatabaseMetaDataTest extends AbstractTest { @Test @Tag("AzureDWTest") public void testDatabaseMetaDataWrapper() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { DatabaseMetaData databaseMetaData = con.getMetaData(); assertTrue(databaseMetaData.isWrapperFor(DatabaseMetaData.class)); assertSame(databaseMetaData, databaseMetaData.unwrap(DatabaseMetaData.class)); @@ -92,13 +91,11 @@ public void testDriverVersion() throws SQLException, IOException { Attributes attributes = manifest.getMainAttributes(); String buildVersion = attributes.getValue("Bundle-Version"); - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - + try (Connection conn = getConnection()) { DatabaseMetaData dbmData = conn.getMetaData(); - String driverVersion = dbmData.getDriverVersion(); - boolean isSnapshot = buildVersion.contains("SNAPSHOT"); + // boolean isSnapshot = buildVersion.contains("SNAPSHOT"); // Removing all dots & chars easy for comparing. driverVersion = driverVersion.replaceAll("[^0-9]", ""); @@ -123,13 +120,13 @@ public void testDriverVersion() throws SQLException, IOException { @Test @Tag("AzureDWTest") public void testGetURL() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { DatabaseMetaData databaseMetaData = conn.getMetaData(); String url = databaseMetaData.getURL(); url = url.toLowerCase(); assertFalse(url.contains("password"), TestResource.getResource("R_getURLContainsPwd")); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -140,11 +137,9 @@ public void testGetURL() throws SQLException { */ @Test public void testDBUserLogin() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { DatabaseMetaData databaseMetaData = conn.getMetaData(); - String connectionString = getConnectionString(); - connectionString = connectionString.toLowerCase(); int startIndex = 0; @@ -152,11 +147,11 @@ public void testDBUserLogin() throws SQLException { if (connectionString.contains("username")) { startIndex = connectionString.indexOf("username="); - endIndex = connectionString.indexOf(";", startIndex); + endIndex = connectionString.indexOf(Constants.SEMI_COLON, startIndex); startIndex = startIndex + "username=".length(); } else if (connectionString.contains("user")) { startIndex = connectionString.indexOf("user="); - endIndex = connectionString.indexOf(";", startIndex); + endIndex = connectionString.indexOf(Constants.SEMI_COLON, startIndex); startIndex = startIndex + "user=".length(); } @@ -164,11 +159,10 @@ public void testDBUserLogin() throws SQLException { String userName = databaseMetaData.getUserName(); assertNotNull(userName, TestResource.getResource("R_userNameNull")); - assertTrue(userName.equalsIgnoreCase(userFromConnectionString), TestResource.getResource("R_userNameNotMatch")); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -180,8 +174,7 @@ public void testDBUserLogin() throws SQLException { @Test @Tag("AzureDWTest") public void testDBSchema() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - ResultSet rs = conn.getMetaData().getSchemas()) { + try (Connection conn = getConnection(); ResultSet rs = conn.getMetaData().getSchemas()) { MessageFormat form = new MessageFormat(TestResource.getResource("R_nameEmpty")); Object[] msgArgs = {"Schema"}; @@ -189,7 +182,7 @@ public void testDBSchema() throws SQLException { assertTrue(!StringUtils.isEmpty(rs.getString(1)), form.format(msgArgs)); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -205,11 +198,9 @@ public void testDBSchemasForDashedCatalogName() throws SQLException { String testCatalog = "dash-catalog" + id; String testSchema = "some-schema" + id; - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = connection.createStatement()) { TestUtils.dropDatabaseIfExists(testCatalog, stmt); stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); - stmt.execute(String.format("USE [%s]", testCatalog)); stmt.execute(String.format("CREATE SCHEMA [%s]", testSchema)); @@ -242,7 +233,7 @@ public void testDBSchemasForDashedCatalogName() throws SQLException { TestUtils.dropDatabaseIfExists(testCatalog, stmt); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -259,7 +250,7 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { String testCatalog = "dash-catalog" + id; String testSchema = "some-schema" + id; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropDatabaseIfExists(testCatalog, stmt); stmt.execute(String.format("CREATE DATABASE [%s]", testCatalog)); @@ -289,7 +280,7 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { TestUtils.dropDatabaseIfExists(testCatalog, stmt); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -307,7 +298,7 @@ public void testDBSchemasForDashedCatalogNameWithPattern() throws SQLException { */ public void testDBTables() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { DatabaseMetaData databaseMetaData = con.getMetaData(); try (ResultSet rsCatalog = databaseMetaData.getCatalogs()) { @@ -343,7 +334,7 @@ public void testDBTables() throws SQLException { @Tag("AzureDWTest") public void testGetDBColumn() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { DatabaseMetaData databaseMetaData = conn.getMetaData(); String[] types = {"TABLE"}; @@ -375,7 +366,7 @@ public void testGetDBColumn() throws SQLException { } } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -391,7 +382,7 @@ public void testGetDBColumn() throws SQLException { @Test public void testGetColumnPrivileges() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { DatabaseMetaData databaseMetaData = conn.getMetaData(); String[] types = {"TABLE"}; try (ResultSet rsTables = databaseMetaData.getTables(null, null, "%", types)) { @@ -420,7 +411,7 @@ public void testGetColumnPrivileges() throws SQLException { } } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -432,7 +423,7 @@ public void testGetColumnPrivileges() throws SQLException { @Test @Tag("AzureDWTest") public void testGetFunctionsWithWrongParams() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { conn.getMetaData().getFunctions("", null, "xp_%"); assertTrue(false, TestResource.getResource("R_noSchemaShouldFail")); } catch (Exception ae) {} @@ -446,8 +437,7 @@ public void testGetFunctionsWithWrongParams() throws SQLException { @Test @Tag("AzureDWTest") public void testGetFunctions() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); - ResultSet rs = conn.getMetaData().getFunctions(null, null, "xp_%")) { + try (Connection conn = getConnection(); ResultSet rs = conn.getMetaData().getFunctions(null, null, "xp_%")) { MessageFormat form = new MessageFormat(TestResource.getResource("R_nameNull")); Object[][] msgArgs = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"NUM_INPUT_PARAMS"}, @@ -462,7 +452,7 @@ public void testGetFunctions() throws SQLException { assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_TYPE")), form.format(msgArgs[6])); } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -473,7 +463,7 @@ public void testGetFunctions() throws SQLException { @Test @Tag("AzureDWTest") public void testGetFunctionColumns() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { DatabaseMetaData databaseMetaData = conn.getMetaData(); @@ -504,13 +494,13 @@ public void testGetFunctionColumns() throws SQLException { } } } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @Test public void testPreparedStatementMetadataCaching() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString)) { + try (Connection connection = getConnection()) { DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = {"TABLE"}; diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BigIntegerTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BigIntegerTest.java index 4a63ec894..413e29ded 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BigIntegerTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BigIntegerTest.java @@ -4,7 +4,6 @@ import java.math.BigInteger; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -40,7 +39,7 @@ enum TestType { */ @Test public void testBigInteger() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { // Create the test table 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 b6345e438..9a2eda3a1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java @@ -9,7 +9,6 @@ import java.math.BigDecimal; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -44,7 +43,7 @@ public class BulkCopyWithSqlVariantTest extends AbstractTest { */ @Test public void bulkCopyTestInt() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { int col1Value = 5; beforeEachSetup("int", col1Value); @@ -74,7 +73,7 @@ public void bulkCopyTestInt() throws SQLException { */ @Test public void bulkCopyTestSmallInt() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { int col1Value = 5; beforeEachSetup("smallint", col1Value); @@ -107,7 +106,7 @@ public void bulkCopyTestSmallInt() throws SQLException { */ @Test public void bulkCopyTestTinyint() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { int col1Value = 5; beforeEachSetup("tinyint", col1Value); @@ -140,7 +139,7 @@ public void bulkCopyTestTinyint() throws SQLException { */ @Test public void bulkCopyTestBigint() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { int col1Value = 5; beforeEachSetup("bigint", col1Value); @@ -172,7 +171,7 @@ public void bulkCopyTestBigint() throws SQLException { */ @Test public void bulkCopyTestFloat() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { int col1Value = 5; beforeEachSetup("float", col1Value); @@ -205,7 +204,7 @@ public void bulkCopyTestFloat() throws SQLException { */ @Test public void bulkCopyTestReal() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { int col1Value = 5; beforeEachSetup("real", col1Value); @@ -238,7 +237,7 @@ public void bulkCopyTestReal() throws SQLException { */ @Test public void bulkCopyTestMoney() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { String col1Value = "126.1230"; beforeEachSetup("money", col1Value); @@ -270,7 +269,7 @@ public void bulkCopyTestMoney() throws SQLException { */ @Test public void bulkCopyTestSmallmoney() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "126.1230"; TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); @@ -307,7 +306,7 @@ public void bulkCopyTestSmallmoney() throws SQLException { */ @Test public void bulkCopyTestDate() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "2015-05-05"; beforeEachSetup("date", "'" + col1Value + "'"); @@ -337,7 +336,7 @@ public void bulkCopyTestDate() throws SQLException { */ @Test public void bulkCopyTestTwoCols() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "2015-05-05"; String col2Value = "126.1230"; @@ -377,7 +376,7 @@ public void bulkCopyTestTwoCols() throws SQLException { */ @Test public void bulkCopyTestTimeWithScale() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "'12:26:27.1452367'"; beforeEachSetup("time(2)", col1Value); @@ -405,7 +404,7 @@ public void bulkCopyTestTimeWithScale() throws SQLException { */ @Test public void bulkCopyTestChar() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "'sample'"; @@ -435,7 +434,7 @@ public void bulkCopyTestChar() throws SQLException { */ @Test public void bulkCopyTestNchar() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "'a'"; @@ -464,7 +463,7 @@ public void bulkCopyTestNchar() throws SQLException { */ @Test public void bulkCopyTestVarchar() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "'hello'"; @@ -494,7 +493,7 @@ public void bulkCopyTestVarchar() throws SQLException { */ @Test public void bulkCopyTestNvarchar() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "'hello'"; beforeEachSetup("nvarchar", col1Value); @@ -523,7 +522,7 @@ public void bulkCopyTestNvarchar() throws SQLException { */ @Test public void bulkCopyTestBinary20() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "hello"; beforeEachSetup("binary(20)", "'" + col1Value + "'"); @@ -553,7 +552,7 @@ public void bulkCopyTestBinary20() throws SQLException { */ @Test public void bulkCopyTestVarbinary20() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "hello"; @@ -583,7 +582,7 @@ public void bulkCopyTestVarbinary20() throws SQLException { */ @Test public void bulkCopyTestVarbinary8000() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "hello"; beforeEachSetup("binary(8000)", "'" + col1Value + "'"); @@ -611,7 +610,7 @@ public void bulkCopyTestVarbinary8000() throws SQLException { */ @Test public void bulkCopyTestBitNull() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { beforeEachSetup("bit", null); @@ -640,7 +639,7 @@ public void bulkCopyTestBitNull() throws SQLException { */ @Test public void bulkCopyTestBit() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { int col1Value = 5000; beforeEachSetup("bit", col1Value); @@ -669,7 +668,7 @@ public void bulkCopyTestBit() throws SQLException { */ @Test public void bulkCopyTestDatetime() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "2015-05-08 12:26:24.0"; beforeEachSetup("datetime", "'" + col1Value + "'"); @@ -700,7 +699,7 @@ public void bulkCopyTestDatetime() throws SQLException { */ @Test public void bulkCopyTestSmalldatetime() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "2015-05-08 12:26:24"; beforeEachSetup("smalldatetime", "'" + col1Value + "'"); @@ -730,7 +729,7 @@ public void bulkCopyTestSmalldatetime() throws SQLException { */ @Test public void bulkCopyTestDatetime2() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "2015-05-08 12:26:24.12645"; beforeEachSetup("datetime2(2)", "'" + col1Value + "'"); @@ -760,7 +759,7 @@ public void bulkCopyTestDatetime2() throws SQLException { */ @Test public void bulkCopyTestTime() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "'12:26:27.1452367'"; TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); @@ -795,7 +794,7 @@ public void bulkCopyTestTime() throws SQLException { */ @Test public void bulkCopyTestReadGUID() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { String col1Value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; beforeEachSetup("uniqueidentifier", "'" + col1Value + "'"); @@ -825,7 +824,7 @@ public void bulkCopyTestReadGUID() throws SQLException { */ @Test public void bulkCopyTestVarChar8000() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < 8000; i++) { @@ -853,7 +852,7 @@ public void bulkCopyTestVarChar8000() throws SQLException { } private void beforeEachSetup(String colType, Object colValue) throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); @@ -873,7 +872,7 @@ private void beforeEachSetup(String colType, Object colValue) throws SQLExceptio */ @AfterAll public static void afterAll() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DataTypesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DataTypesTest.java index 6c74d768a..323405599 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DataTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DataTypesTest.java @@ -9,7 +9,6 @@ import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Date; -import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -20,6 +19,7 @@ import java.sql.Timestamp; import java.text.DateFormatSymbols; import java.text.MessageFormat; +import java.time.Instant; import java.util.Calendar; import java.util.EnumSet; import java.util.GregorianCalendar; @@ -41,6 +41,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.PrepUtil; import microsoft.sql.DateTimeOffset; @@ -1063,7 +1064,7 @@ enum TestValue { @Test public void testResultSetGetters() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { for (TestValue value : TestValue.values()) value.sqlValue.verifyRSGetters(conn); } @@ -1071,7 +1072,7 @@ public void testResultSetGetters() throws Exception { @Test public void testResultSetUpdaters() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { for (TestValue value : TestValue.values()) value.sqlValue.verifyRSUpdaters(conn); } @@ -1079,7 +1080,7 @@ public void testResultSetUpdaters() throws Exception { @Test public void testSetters() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDateTime=true")) { + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDateTime=true")) { for (TestValue value : TestValue.values()) value.sqlValue.verifySetters(conn); } @@ -1087,7 +1088,7 @@ public void testSetters() throws Exception { @Test public void testCallableStatementGetters() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { for (TestValue value : TestValue.values()) value.sqlValue.verifyCSGetters(conn); } @@ -1095,7 +1096,7 @@ public void testCallableStatementGetters() throws Exception { @Test public void testResultSetMetaData() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { for (TestValue value : TestValue.values()) value.sqlValue.verifyResultSetMetaData(conn); } @@ -1103,7 +1104,7 @@ public void testResultSetMetaData() throws Exception { @Test public void testParameterMetaData() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { for (TestValue value : TestValue.values()) value.sqlValue.verifyParameterMetaData(conn); } ; @@ -1114,7 +1115,7 @@ public void testParameterMetaData() throws Exception { */ @Test public void testSendTimestampAsTimeAsDatetime() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=true")) { + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=true")) { try (Statement stmt = conn.createStatement()) { TestUtils.dropProcedureIfExists(escapedProcName, stmt); stmt.executeUpdate("CREATE PROCEDURE " + escapedProcName + " @argIn time(7), " @@ -1153,7 +1154,7 @@ public void testSendTimestampAsTimeAsDatetime() throws Exception { */ @Test public void testDoubleRounding() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { // create a table with a datetimeoffset column and insert a value in it assumeTrue(!isSqlAzureDW(), TestResource.getResource("R_skipAzure")); @@ -1236,7 +1237,7 @@ public void testWithJapaneseImperialCalendar() throws Exception { Locale defaultLocale = Locale.getDefault(); Locale.setDefault(japaneseImperialLocale); - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=true")) { + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=true")) { // Get Gregorian date using Japanese imperial calendar try (ResultSet rs = conn.createStatement().executeQuery("SELECT CAST('0821-01-04' AS DATE)")) { @@ -1325,7 +1326,7 @@ enum StringFormatTestValue { @Test public void testGetString() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { for (StringFormatTestValue testValue : EnumSet.allOf(StringFormatTestValue.class)) { String query = "SELECT " + "CAST('" + testValue.sqlLiteral + "' AS " + testValue.sqlType + "), " @@ -1349,7 +1350,7 @@ public void testWithThaiLocale() throws Exception { Locale locale = Locale.getDefault(); Locale.setDefault(new Locale("th", "TH")); - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=true")) { + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=true")) { // Test setter conversions try (PreparedStatement ps = conn.prepareStatement("SELECT CAST(? AS VARCHAR(40))")) { @@ -1436,7 +1437,7 @@ public void testBaseDate() throws Exception { Timestamp ts; // Test Java base date (1/1/1970) - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=true"); + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=true"); PreparedStatement ps = conn.prepareStatement("SELECT CAST(? AS DATETIME)")) { ps.setTime(1, java.sql.Time.valueOf("12:34:56")); @@ -1449,7 +1450,7 @@ public void testBaseDate() throws Exception { } // Test SQL Server base date (1/1/1900) - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false"); PreparedStatement ps = conn.prepareStatement("SELECT CAST(? AS DATETIME)")) { ps.setTime(1, java.sql.Time.valueOf("12:34:56")); @@ -1465,7 +1466,7 @@ public void testBaseDate() throws Exception { // test setTimestamp to DATETIMEOFFSET yields a value in local time with UTC time zone offset (+00:00) @Test public void testTimestampToDateTimeOffset() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT CAST(? AS DATETIMEOFFSET)")) { ps.setTimestamp(1, Timestamp.valueOf("2010-01-06 12:34:56")); @@ -1483,7 +1484,7 @@ public void testTimestampToDateTimeOffset() throws Exception { */ @Test public void testJulianLeapYear() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=true"); + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=true"); // PreparedStatement ps = conn.prepareStatement("SELECT CAST(? AS VARCHAR)"); PreparedStatement ps = conn.prepareStatement("SELECT CAST(? AS DATE)")) { @@ -1499,7 +1500,7 @@ public void testJulianLeapYear() throws Exception { @Test public void testGetTimeRounding() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=true"); + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=true"); Statement stmt = conn.createStatement()) { // Test getTime() rounding from TIME(6) SQL type @@ -1518,7 +1519,7 @@ public void testGetTimeRounding() throws Exception { @Test public void testGregorianCutoverDateTime2() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=true"); + try (Connection conn = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=true"); PreparedStatement ps = conn.prepareStatement("SELECT CAST(? AS VARCHAR)")) { Timestamp ts; @@ -1551,7 +1552,7 @@ public void testGregorianCutoverDateTime2() throws Exception { */ @Test public void testTimestampToDateTime() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); PreparedStatement ps = conn + try (Connection conn = getConnection(); PreparedStatement ps = conn .prepareStatement("SELECT 1 WHERE ?=CAST('2009-12-17 17:00:29' AS DATETIME)")) { ps.setTimestamp(1, Timestamp.valueOf("2009-12-17 17:00:29")); try (ResultSet rs = ps.executeQuery()) { @@ -1562,7 +1563,7 @@ public void testTimestampToDateTime() throws Exception { @Test public void testUpdateMisc() throws Exception { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager + try (SQLServerConnection conn = (SQLServerConnection) PrepUtil .getConnection(connectionString + ";sendTimeAsDatetime=true")) { assumeTrue(!isSqlAzureDW(), TestResource.getResource("R_skipAzure")); @@ -1653,10 +1654,10 @@ public void testUpdateMisc() throws Exception { assertEquals("1970-01-01 23:59:59.0", new Timestamp(rs.getTime(6).getTime()).toString()); // Update datetime w/expected rounding of nanos to DATETIME's 1/300second resolution - ts = Timestamp.valueOf("6289-04-22 05:13:57.6745106"); + ts = Timestamp.valueOf("6289-04-22 05:13:57.6741234"); rs.updateTimestamp(2, ts); rs.updateRow(); - assertEquals("6289-04-22 05:13:57.677", rs.getTimestamp(2).toString()); + assertEquals("6289-04-22 05:13:57.673", rs.getTimestamp(2).toString()); // Update datetime with rounding-induced overflow from Time (should roll date part to 1/2/1970) ts = Timestamp.valueOf("2010-01-18 23:59:59.999"); @@ -1670,4 +1671,122 @@ public void testUpdateMisc() throws Exception { } } } + + /* + * SQL Server compatibility level >= 130 (SQL Server 2016 and after) doesn't round up or down equally for datetime. + * The rounding logic below represents the actual rounding logic employed by datetime columns when determining their + * last millisecond digit. + */ + @Test + public void testDateTimeInsertUpdate() throws Exception { + assumeTrue(!isSqlAzureDW(), TestResource.getResource("R_cursorAzureDW")); + + try (Connection conn = getConnection(); + Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + escapedTableName + " VALUES (?)")) { + TestUtils.dropTableIfExists(escapedTableName, stmt); + + stmt.executeUpdate("CREATE TABLE " + escapedTableName + " (c1 datetime)"); + + String testValue2 = "2012-06-18T10:34:09Z"; + Instant ist = Instant.parse(testValue2); + ist = ist.plusNanos(634999949); + DateTimeOffset dto1 = DateTimeOffset.valueOf(Timestamp.from(ist), 0); + + pstmt.setObject(1, dto1); + pstmt.addBatch(); + + ist = Instant.parse(testValue2); + ist = ist.plusNanos(634999950); + DateTimeOffset dto2 = DateTimeOffset.valueOf(Timestamp.from(ist), 0); + + pstmt.setObject(1, dto2); + pstmt.addBatch(); + + ist = Instant.parse(testValue2); + ist = ist.plusNanos(741666649); + DateTimeOffset dto3 = DateTimeOffset.valueOf(Timestamp.from(ist), 0); + + pstmt.setObject(1, dto3); + pstmt.addBatch(); + + ist = Instant.parse(testValue2); + ist = ist.plusNanos(741666650); + DateTimeOffset dto4 = DateTimeOffset.valueOf(Timestamp.from(ist), 0); + + pstmt.setObject(1, dto4); + pstmt.addBatch(); + + ist = Instant.parse(testValue2); + ist = ist.plusNanos(788333349); + DateTimeOffset dto5 = DateTimeOffset.valueOf(Timestamp.from(ist), 0); + + pstmt.setObject(1, dto5); + pstmt.addBatch(); + + ist = Instant.parse(testValue2); + ist = ist.plusNanos(788333350); + DateTimeOffset dto6 = DateTimeOffset.valueOf(Timestamp.from(ist), 0); + + pstmt.setObject(1, dto6); + pstmt.addBatch(); + + pstmt.executeBatch(); + + int serverVersion = conn.getMetaData().getDatabaseMajorVersion(); + + String[] result = new String[6]; + result[0] = "2012-06-18 10:34:09.633"; + result[1] = "2012-06-18 10:34:09.637"; + result[2] = "2012-06-18 10:34:09.74"; + result[3] = "2012-06-18 10:34:09.743"; + result[4] = "2012-06-18 10:34:09.787"; + result[5] = "2012-06-18 10:34:09.79"; + + String[] resultPre2k16 = new String[6]; + resultPre2k16[0] = "2012-06-18 10:34:09.637"; + resultPre2k16[1] = "2012-06-18 10:34:09.637"; + resultPre2k16[2] = "2012-06-18 10:34:09.743"; + resultPre2k16[3] = "2012-06-18 10:34:09.743"; + resultPre2k16[4] = "2012-06-18 10:34:09.787"; + resultPre2k16[5] = "2012-06-18 10:34:09.787"; + + DateTimeOffset[] dto = new DateTimeOffset[6]; + dto[0] = dto1; + dto[1] = dto2; + dto[2] = dto3; + dto[3] = dto4; + dto[4] = dto5; + dto[5] = dto6; + + try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + escapedTableName + " ORDER BY c1")) { + if (serverVersion >= 13.0 || TestUtils.isAzure(conn)) { + for (int i = 0; i < result.length; i++) { + rs.next(); + assertEquals(rs.getObject(1).toString(), result[i]); + } + + for (int i = 0; i < result.length; i++) { + rs.updateObject(1, dto[i]); + rs.updateRow(); + assertEquals(rs.getObject(1).toString(), result[i]); + } + } else { + for (int i = 0; i < result.length; i++) { + rs.next(); + assertEquals(rs.getObject(1).toString(), resultPre2k16[i]); + } + + for (int i = 0; i < result.length; i++) { + rs.updateObject(1, dto[i]); + rs.updateRow(); + assertEquals(rs.getObject(1).toString(), resultPre2k16[i]); + } + } + } finally { + TestUtils.dropTableIfExists(escapedTableName, 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 83496b2dd..f341789e1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java @@ -9,7 +9,6 @@ import java.sql.Connection; import java.sql.Date; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -32,6 +31,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -52,7 +52,7 @@ public class DateAndTimeTypeTest extends AbstractTest { */ @Test public void testQueryDate() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false")) { String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + " where my_date = ?"; @@ -72,7 +72,7 @@ public void testQueryDate() throws SQLException { */ @Test public void testQueryTimestamp() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false")) { String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + " where my_timestamp = ?"; @@ -92,7 +92,7 @@ public void testQueryTimestamp() throws SQLException { */ @Test public void testQueryTime() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false")) { String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + " where my_time = ?"; @@ -112,7 +112,7 @@ public void testQueryTime() throws SQLException { */ @Test public void testQueryDateTVP() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false")) { SQLServerDataTable tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", java.sql.Types.DATE); @@ -136,7 +136,7 @@ public void testQueryDateTVP() throws SQLException { */ @Test public void testQueryTimestampTVP() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false")) { SQLServerDataTable tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", java.sql.Types.TIMESTAMP); @@ -160,7 +160,7 @@ public void testQueryTimestampTVP() throws SQLException { */ @Test public void testQueryTimeTVP() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false")) { SQLServerDataTable tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", java.sql.Types.TIME); @@ -180,7 +180,7 @@ public void testQueryTimeTVP() throws SQLException { } private void createTVPs(String tvpName, String tvpType) throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false"); Statement stmt = (SQLServerStatement) connection.createStatement()) { stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" @@ -200,7 +200,7 @@ public void testSetup() throws TestAbortedException, Exception { // To get TIME & setTime working on Servers >= 2008, we must add 'sendTimeAsDatetime=false' // by default to the connection. See issue https://github.com/Microsoft/mssql-jdbc/issues/559 - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false"); Statement stmt = (SQLServerStatement) connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -227,8 +227,8 @@ public void testSetup() throws TestAbortedException, Exception { @AfterAll public static void terminateVariation() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); - Statement stmt = (SQLServerStatement) connection.createStatement()) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";sendTimeAsDatetime=false"); + Statement stmt = connection.createStatement()) { 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 a2cde12b7..bf293d5db 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java @@ -9,7 +9,6 @@ import java.io.IOException; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -304,8 +303,7 @@ public void testCurvePolygonWkt() throws SQLException { @Test public void testFullGlobeWkt() throws SQLException { - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { if (isDenaliOrLater) { beforeEachSetup(); @@ -479,8 +477,7 @@ public void testAllTypes() throws SQLException { Geography geogWKT; // Geometry - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)")) { @@ -634,8 +631,7 @@ public void testMixedAllTypes() throws SQLException { Geometry geomWKT; Geography geogWKT; - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) + " values (?, ?, ?, ?, ?)");) { @@ -774,8 +770,7 @@ public void testParse() throws SQLException { Geometry geomWKT = Geometry.parse(geoWKT); Geography geogWKT = Geography.parse(geoWKT); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { @@ -815,8 +810,7 @@ public void testPoint() throws SQLException { Geometry geomWKT = Geometry.point(1, 2, 0); Geography geogWKT = Geography.point(2, 1, 4326); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { @@ -856,8 +850,7 @@ public void testSTAsText() throws SQLException { Geometry geomWKT = Geometry.STGeomFromText(geoWKT, 0); Geography geogWKT = Geography.STGeomFromText(geoWKT, 4326); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { @@ -911,8 +904,7 @@ public void testSTAsBinary() throws SQLException { public void testCheckGeomMetaData() throws SQLException { beforeEachSetup(); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); @@ -936,8 +928,7 @@ public void testCheckGeomMetaData() throws SQLException { public void testCheckGeogMetaData() throws SQLException { beforeEachSetup(); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); @@ -1001,8 +992,7 @@ public void testNull() throws SQLException { Geometry geomWKT; Geography geogWKT; - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) @@ -1050,8 +1040,7 @@ public void testWrongtype() throws SQLException { Geometry geomWKT = Geometry.point(1, 2, 0); Geography geogWKT = Geography.point(2, 1, 4326); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { @@ -1088,8 +1077,7 @@ public void testWrongtype() throws SQLException { } private void beforeEachSetup() throws SQLException { - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geomTableName), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geogTableName), stmt); stmt.executeUpdate( @@ -1100,8 +1088,7 @@ private void beforeEachSetup() throws SQLException { } private void beforeEachSetupSpatialDatatype() throws SQLException { - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { 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)"); @@ -1116,8 +1103,7 @@ private void testWkt(String geoWKT, String geoWKTSS) throws SQLException { Geometry geomWKT = Geometry.STGeomFromText(geoWKT, 0); Geography geogWKT = Geography.STGeomFromText(geoWKT, 4326); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { @@ -1168,8 +1154,8 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti geogTableName = RandomUtil.getIdentifier("geographyTestTable"); spatialDatatypeTableName = RandomUtil.getIdentifier("spatialDatatypeTestTable"); - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(); + SQLServerResultSet rs = (SQLServerResultSet) stmt .executeQuery("select SERVERPROPERTY ( 'ProductVersion' )")) { rs.next(); @@ -1194,8 +1180,7 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { 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 babee66d8..d1615fb7e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java @@ -11,7 +11,6 @@ import java.io.IOException; import java.math.BigDecimal; import java.sql.CallableStatement; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -54,8 +53,7 @@ public class SQLVariantResultSetTest extends AbstractTest { */ @Test public void readInt() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { int value = 2; createAndPopulateTable("int", value); @@ -75,8 +73,7 @@ public void readInt() throws SQLException, SecurityException, IOException { */ @Test public void readMoney() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { Double value = 123.12; createAndPopulateTable("Money", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -94,8 +91,7 @@ public void readMoney() throws SQLException { */ @Test public void readSmallMoney() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { Double value = 123.12; createAndPopulateTable("smallmoney", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -113,8 +109,7 @@ public void readSmallMoney() throws SQLException { */ @Test public void readGUID() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; createAndPopulateTable("uniqueidentifier", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -132,8 +127,7 @@ public void readGUID() throws SQLException { */ @Test public void readDate() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "'2015-05-08'"; createAndPopulateTable("date", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -151,8 +145,7 @@ public void readDate() throws SQLException { */ @Test public void readTime() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "'12:26:27.123345'"; createAndPopulateTable("time(3)", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -170,8 +163,7 @@ public void readTime() throws SQLException { */ @Test public void readDateTime() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "'2015-05-08 12:26:24'"; createAndPopulateTable("datetime", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -189,8 +181,7 @@ public void readDateTime() throws SQLException { */ @Test public void readSmallDateTime() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "'2015-05-08 12:26:24'"; createAndPopulateTable("smalldatetime", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -214,8 +205,8 @@ public void readVarChar8000() throws SQLException { } String value = "'" + buffer.toString() + "'"; createAndPopulateTable("VARCHAR(8000)", value); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(); + SQLServerResultSet rs = (SQLServerResultSet) stmt .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); assertEquals(rs.getObject(1), buffer.toString()); @@ -229,8 +220,7 @@ public void readVarChar8000() throws SQLException { */ @Test public void readFloat() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { float value = 5; createAndPopulateTable("float", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -248,8 +238,7 @@ public void readFloat() throws SQLException { */ @Test public void readBigInt() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { long value = 5; createAndPopulateTable("bigint", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -267,8 +256,7 @@ public void readBigInt() throws SQLException { */ @Test public void readSmallInt() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { short value = 5; createAndPopulateTable("smallint", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -286,8 +274,7 @@ public void readSmallInt() throws SQLException { */ @Test public void readTinyInt() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { short value = 5; createAndPopulateTable("tinyint", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -305,8 +292,7 @@ public void readTinyInt() throws SQLException { */ @Test public void readBit() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { int value = 50000; createAndPopulateTable("bit", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -324,8 +310,7 @@ public void readBit() throws SQLException { */ @Test public void readReal() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { float value = 5; createAndPopulateTable("Real", value); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -343,8 +328,7 @@ public void readReal() throws SQLException { */ @Test public void readNChar() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "a"; createAndPopulateTable("nchar(5)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -364,8 +348,7 @@ public void readNChar() throws SQLException, SecurityException, IOException { */ @Test public void readNVarChar() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "nvarchar"; createAndPopulateTable("nvarchar(10)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -385,8 +368,7 @@ public void readNVarChar() throws SQLException, SecurityException, IOException { */ @Test public void readBinary20() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "hi"; createAndPopulateTable("binary(20)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -406,8 +388,7 @@ public void readBinary20() throws SQLException, SecurityException, IOException { */ @Test public void readVarBinary20() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "hi"; createAndPopulateTable("varbinary(20)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -427,8 +408,7 @@ public void readVarBinary20() throws SQLException, SecurityException, IOExceptio */ @Test public void readBinary512() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "hi"; createAndPopulateTable("binary(512)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -448,8 +428,7 @@ public void readBinary512() throws SQLException, SecurityException, IOException */ @Test public void readBinary8000() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "hi"; createAndPopulateTable("binary(8000)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -469,8 +448,7 @@ public void readBinary8000() throws SQLException, SecurityException, IOException */ @Test public void readvarBinary8000() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "hi"; createAndPopulateTable("varbinary(8000)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -490,8 +468,7 @@ public void readvarBinary8000() throws SQLException, SecurityException, IOExcept */ @Test public void readSQLVariantProperty() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "hi"; createAndPopulateTable("binary(8000)", "'" + value + "'"); try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( @@ -515,19 +492,18 @@ public void insertVarChar8001() throws SQLException { for (int i = 0; i < 8001; i++) { buffer.append("a"); } - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); 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")); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?)")) { + pstmt.setObject(1, buffer.toString()); + try { + pstmt.execute(); + } catch (SQLServerException e) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_OperandTypeClash"))); + } } } } @@ -545,8 +521,7 @@ public void readNvarChar4000() throws SQLException { } String value = "'" + buffer.toString() + "'"; createAndPopulateTable("NVARCHAR(4000)", value); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { try (SQLServerResultSet rs = (SQLServerResultSet) stmt .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); @@ -564,7 +539,7 @@ public void readNvarChar4000() throws SQLException { */ @Test public void UpdateInt() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { int value = 2; int updatedValue = 3; @@ -593,7 +568,7 @@ public void UpdateInt() throws SQLException, SecurityException, IOException { */ @Test public void UpdateNChar() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { String value = "a"; String updatedValue = "b"; @@ -624,7 +599,7 @@ public void UpdateNChar() throws SQLException, SecurityException, IOException { */ @Test public void updateBinary20() throws SQLException, SecurityException, IOException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { String value = "hi"; String updatedValue = "bye"; @@ -652,32 +627,31 @@ public void updateBinary20() throws SQLException, SecurityException, IOException */ @Test public void insertTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); 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 (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?, ?)")) { - 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()); + 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()); + } } } } @@ -689,8 +663,7 @@ public void insertTest() throws SQLException { */ @Test public void insertTestNull() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); stmt.executeUpdate( "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); @@ -716,8 +689,7 @@ public void insertTestNull() throws SQLException { */ @Test public void insertSetObject() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); stmt.executeUpdate( "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); @@ -743,8 +715,7 @@ public void insertSetObject() throws SQLException { */ @Test public void callableStatementOutputIntTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { int value = 5; TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); stmt.executeUpdate( @@ -758,13 +729,11 @@ public void callableStatementOutputIntTest() throws SQLException { + 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(); + try (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)); } } } @@ -776,8 +745,7 @@ public void callableStatementOutputIntTest() throws SQLException { */ @Test public void callableStatementOutputDateTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "2015-05-08"; TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); @@ -792,13 +760,11 @@ public void callableStatementOutputDateTest() throws SQLException { + 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(); + try (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)); } } } @@ -810,8 +776,7 @@ public void callableStatementOutputDateTest() throws SQLException { */ @Test public void callableStatementOutputTimeTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String value = "12:26:27.123345"; String returnValue = "12:26:27"; TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); @@ -826,13 +791,11 @@ public void callableStatementOutputTimeTest() throws SQLException { + 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(); + try (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)); } } } @@ -844,8 +807,7 @@ public void callableStatementOutputTimeTest() throws SQLException { */ @Test public void callableStatementOutputBinaryTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { byte[] binary20 = RandomData.generateBinaryTypes("20", false, false); byte[] secondBinary20 = RandomData.generateBinaryTypes("20", false, false); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); @@ -864,15 +826,12 @@ public void callableStatementOutputBinaryTest() throws SQLException { + 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(); + try (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)); } } } @@ -884,8 +843,7 @@ public void callableStatementOutputBinaryTest() throws SQLException { */ @Test public void callableStatementInputOutputIntTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { int col1Value = 5; int col2Value = 2; TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); @@ -898,15 +856,13 @@ public void callableStatementInputOutputIntTest() throws SQLException { + " @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(); + try (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); } } } @@ -918,8 +874,7 @@ public void callableStatementInputOutputIntTest() throws SQLException { */ @Test public void callableStatementInputOutputReturnIntTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { int col1Value = 5; int col2Value = 2; int returnValue = 12; @@ -933,17 +888,15 @@ public void callableStatementInputOutputReturnIntTest() throws SQLException { + " @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(); + try (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)); } } } @@ -955,8 +908,7 @@ public void callableStatementInputOutputReturnIntTest() throws SQLException { */ @Test public void callableStatementInputOutputReturnStringTest() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String col1Value = "aa"; String col2Value = "bb"; int returnValue = 12; @@ -972,17 +924,15 @@ public void callableStatementInputOutputReturnStringTest() throws SQLException { + " @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(); + try (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); } } } @@ -994,8 +944,7 @@ public void callableStatementInputOutputReturnStringTest() throws SQLException { */ @Test public void readSeveralRows() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { short value1 = 5; int value2 = 10; String value3 = "hi"; @@ -1023,8 +972,7 @@ public void readSeveralRows() throws SQLException { */ @Test public void readVarcharInteger() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { Object expected[] = {"abc", 42}; int index = 0; try (SQLServerResultSet rs = (SQLServerResultSet) stmt @@ -1043,18 +991,15 @@ public void readVarcharInteger() throws SQLException { */ @Test public void testUnsupportedDatatype() throws SQLException { - 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.")); - } + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement(); + 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.")); } } } @@ -1067,8 +1012,8 @@ public void testUnsupportedDatatype() throws SQLException { */ @Test public void testTimeClassAsSqlVariant() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + try (SQLServerConnection con = (SQLServerConnection) getConnection(); 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); @@ -1093,8 +1038,7 @@ private boolean parseByte(byte[] expectedData, byte[] retrieved) { * @throws SQLException */ private void createAndPopulateTable(String columnType, Object value) throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); stmt.executeUpdate( "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); @@ -1123,8 +1067,7 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); 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/SparseTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SparseTest.java index 436e62089..69465311b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SparseTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SparseTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; @@ -26,7 +25,7 @@ public class SparseTest extends AbstractTest { @Test public void testSparse() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { assumeTrue(!isSqlAzureDW(), TestResource.getResource("R_skipAzure")); try (Statement stmt = conn.createStatement()) { 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 135816a2e..3f9676dc1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -10,7 +10,6 @@ import java.math.BigDecimal; import java.sql.Date; -import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLTimeoutException; @@ -32,6 +31,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.PrepUtil; import com.microsoft.sqlserver.testframework.sqlType.SqlDate; @@ -465,8 +465,7 @@ private static String[] createNumericValues() { @BeforeEach public void testSetup() throws SQLException { - conn = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";sendStringParametersAsUnicode=true;"); + conn = (SQLServerConnection) PrepUtil.getConnection(connectionString + ";sendStringParametersAsUnicode=true;"); stmt = (SQLServerStatement) conn.createStatement(); TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ErrorStateTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ErrorStateTest.java index e57b9055f..e3eec336f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ErrorStateTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ErrorStateTest.java @@ -9,7 +9,6 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -18,7 +17,7 @@ public class ErrorStateTest extends AbstractTest { @Test public void testSQLStateNegative() throws Exception { int state = -1; // Negative error raised converts to positive SQL State (1) - try (Connection con = PrepUtil.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.execute("RAISERROR (13002, -1, " + state + ", N'Testing error');"); } catch (SQLException e) { assert (e.getSQLState().length() == 5); @@ -28,7 +27,7 @@ public void testSQLStateNegative() throws Exception { @Test public void testSQLStateLength1() throws Exception { - try (Connection con = PrepUtil.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.execute("SELECT 1/0;"); } catch (SQLException e) { assert (e.getSQLState().length() == 5); @@ -39,7 +38,7 @@ public void testSQLStateLength1() throws Exception { @Test public void testSQLStateLength2() throws Exception { int state = 31; - try (Connection con = PrepUtil.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.execute("RAISERROR (13002, -1, " + state + ", N'Testing error');"); } catch (SQLException e) { assert (e.getSQLState().length() == 5); @@ -50,7 +49,7 @@ public void testSQLStateLength2() throws Exception { @Test public void testSQLStateLength3() throws Exception { int state = 255; // Max Value of SQL State - try (Connection con = PrepUtil.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.execute("RAISERROR (13003, -1, " + state + ", N'Testing error');"); } catch (SQLException e) { assert (e.getSQLState().length() == 5); 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 d7814f66a..e9079509f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java @@ -9,7 +9,6 @@ import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.text.MessageFormat; @@ -26,6 +25,8 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -37,13 +38,13 @@ public class ExceptionTest extends AbstractTest { * * @throws Exception */ + @SuppressWarnings("resource") @Test public void testBulkCSVFileRecordExceptionCause() throws Exception { String filePath = TestUtils.getCurrentClassPath(); try { - SQLServerBulkCSVFileRecord scvFileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, - "invalid_encoding", true); + new SQLServerBulkCSVFileRecord(filePath + inputFile, "invalid_encoding", true); } catch (Exception e) { if (!(e instanceof SQLException)) { throw e; @@ -67,14 +68,14 @@ public void testBulkCSVFileRecordExceptionCause() throws Exception { */ @Test public void testSocketTimeoutExceptionCause() throws Exception { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection conn = (SQLServerConnection) getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); createWaitForDelayPreocedure(conn); } - try (Connection conn = DriverManager - .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); + try (Connection conn = PrepUtil.getConnection( + connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + Constants.SEMI_COLON); Statement stmt = conn.createStatement()) { stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); @@ -98,7 +99,7 @@ private void createWaitForDelayPreocedure(SQLServerConnection conn) throws SQLEx @AfterAll public static void cleanup() throws SQLException { - try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection conn = (SQLServerConnection) getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java index ad06973a6..50b2d212d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsEnvTest.java @@ -24,6 +24,7 @@ import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -123,7 +124,7 @@ public void testFIPSOnIBM() throws Exception { @Test @Disabled public void testFIPSEnv() { - assumeTrue("FIPS".equals(TestUtils.getConfiguredProperty("FIPS_ENV")), + assumeTrue(Constants.FIPS.equals(TestUtils.getConfiguredProperty(Constants.FIPS_ENV)), TestResource.getResource("R_fipsPropertyNotSet")); // As JDK 1.7 is not supporting lambda for time being commenting. diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java index 134917ec7..2f4d49d3e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/fips/FipsTest.java @@ -11,7 +11,6 @@ import java.util.Properties; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; @@ -21,6 +20,7 @@ import com.microsoft.sqlserver.jdbc.StringUtils; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.PrepUtil;; @@ -31,15 +31,6 @@ @Tag("AzureDWTest") public class FipsTest extends AbstractTest { - private static String connectionString; - private static String[] dataSourceProps; - - @BeforeAll - public static void init() { - connectionString = getConnectionString(); - dataSourceProps = getDataSourceProperties(); - } - /** * Test after setting TrustServerCertificate as true. * @@ -48,7 +39,7 @@ public static void init() { @Test public void fipsTrustServerCertificateTest() throws Exception { Properties props = buildConnectionProperties(); - props.setProperty("TrustServerCertificate", "true"); + props.setProperty(Constants.TRUST_SERVER_CERTIFICATE, Boolean.TRUE.toString()); try (Connection con = PrepUtil.getConnection(connectionString, props)) { Assertions.fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (SQLException e) { @@ -65,7 +56,7 @@ public void fipsTrustServerCertificateTest() throws Exception { @Test public void fipsEncryptTest() throws Exception { Properties props = buildConnectionProperties(); - props.setProperty("encrypt", "false"); + props.setProperty(Constants.ENCRYPT, Boolean.FALSE.toString()); try (Connection con = PrepUtil.getConnection(connectionString, props)) { Assertions.fail(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (SQLException e) { @@ -82,13 +73,13 @@ public void fipsEncryptTest() throws Exception { @Test public void fipsPropertyTest() throws Exception { Properties props = buildConnectionProperties(); - props.remove("fips"); - props.remove("trustStoreType"); - props.remove("encrypt"); + props.remove(Constants.FIPS); + props.remove(Constants.TRUST_STORE_TYPE); + props.remove(Constants.ENCRYPT); try (Connection con = PrepUtil.getConnection(connectionString, props)) { Assertions.assertTrue(!StringUtils.isEmpty(con.getSchema())); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -103,11 +94,11 @@ public void fipsDataSourcePropertyTest() throws Exception { setDataSourceProperties(ds); ds.setFIPS(false); ds.setEncrypt(false); - ds.setTrustStoreType("JKS"); + ds.setTrustStoreType(Constants.JKS); try (Connection con = ds.getConnection()) { Assertions.assertTrue(!StringUtils.isEmpty(con.getSchema())); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } } @@ -153,22 +144,14 @@ public void fipsDataSourceTrustServerCertificateTest() throws Exception { * @param ds */ private void setDataSourceProperties(SQLServerDataSource ds) { - ds.setServerName(dataSourceProps[0]); - - if (dataSourceProps[1] != null && StringUtils.isInteger(dataSourceProps[1])) { - ds.setPortNumber(Integer.valueOf(dataSourceProps[1])); - } - - ds.setUser(dataSourceProps[2]); - ds.setPassword(dataSourceProps[3]); - ds.setDatabaseName(dataSourceProps[4]); + ds = (SQLServerDataSource) updateDataSource(ds); // Set all properties for FIPS ds.setFIPS(true); ds.setEncrypt(true); ds.setTrustServerCertificate(false); ds.setIntegratedSecurity(false); - ds.setTrustStoreType("PKCS12"); + ds.setTrustStoreType(Constants.PKCS12); } /** @@ -179,68 +162,16 @@ private void setDataSourceProperties(SQLServerDataSource ds) { private Properties buildConnectionProperties() { Properties connectionProps = new Properties(); - connectionProps.setProperty("encrypt", "true"); - connectionProps.setProperty("integratedSecurity", "false"); + connectionProps.setProperty(Constants.ENCRYPT, Boolean.TRUE.toString()); + connectionProps.setProperty(Constants.INTEGRATED_SECURITY, Boolean.FALSE.toString()); // In case of false we need to pass keystore etc. which is not passing by default. - connectionProps.setProperty("TrustServerCertificate", "false"); + connectionProps.setProperty(Constants.TRUST_SERVER_CERTIFICATE, Boolean.FALSE.toString()); // For New Code - connectionProps.setProperty("trustStoreType", "PKCS12"); - connectionProps.setProperty("fips", "true"); + connectionProps.setProperty(Constants.TRUST_STORE_TYPE, Constants.PKCS12); + connectionProps.setProperty(Constants.FIPS, Boolean.TRUE.toString()); return connectionProps; } - - /** - * It will return String array. [dbServer,username,password,dbname/database] - * - * @param connectionProperty - * @return - */ - private static String[] getDataSourceProperties() { - String[] params = connectionString.split(";"); - String[] dataSoureParam = new String[5]; - - for (String strParam : params) { - if (strParam.startsWith("jdbc:sqlserver")) { - dataSoureParam[0] = strParam.replace("jdbc:sqlserver://", ""); - String[] hostPort = dataSoureParam[0].split(":"); - dataSoureParam[0] = hostPort[0]; - if (hostPort.length > 1) { - dataSoureParam[1] = hostPort[1]; - } - } - // Actually this is specifically did for Travis. - else if (strParam.startsWith("port")) { - strParam = strParam.toLowerCase(); - if (strParam.startsWith("portnumber")) { - dataSoureParam[1] = strParam.replace("portnumber=", ""); - } else { - dataSoureParam[1] = strParam.replace("port=", ""); - } - } - - else if (strParam.startsWith("user")) { - strParam = strParam.toLowerCase(); - if (strParam.startsWith("username")) { - dataSoureParam[2] = strParam.replace("username=", ""); - } else { - dataSoureParam[2] = strParam.replace("user=", ""); - } - } else if (strParam.startsWith("password")) { - dataSoureParam[3] = strParam.replace("password=", ""); - } else if (strParam.startsWith("database")) { - strParam = strParam.toLowerCase(); - if (strParam.startsWith("databasename")) { - dataSoureParam[4] = strParam.replace("databasename=", ""); - } else { - dataSoureParam[4] = strParam.replace("database=", ""); - } - } - - } - - return dataSoureParam; - } } 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 c4f3151cc..0db893ac4 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; @@ -35,7 +34,7 @@ public class ParameterMetaDataTest extends AbstractTest { */ @Test public void testParameterMetaDataWrapper() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int identity(1,1) primary key)"); @@ -60,7 +59,7 @@ public void testParameterMetaDataWrapper() throws SQLException { */ @Test public void testSQLServerExceptionNotWrapped() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement pstmt = connection.prepareStatement("invalid query :)");) { pstmt.getParameterMetaData(); @@ -77,7 +76,7 @@ public void testSQLServerExceptionNotWrapped() throws SQLException { */ @Test public void testNameWithBraces() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " ([c1_varchar(max)] varchar(max))"); @@ -101,7 +100,7 @@ public void testNameWithBraces() throws SQLException { */ @Test public void testParameterMetaData() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " ([c1_varchar(max)] varchar(max), c2 decimal(38,5))"); @@ -112,14 +111,47 @@ public void testParameterMetaData() throws SQLException { try (PreparedStatement pstmt = con.prepareStatement(query)) { ParameterMetaData metadata = pstmt.getParameterMetaData(); assert (metadata.getParameterCount() == 2); + assert (metadata.getParameterType(1) == java.sql.Types.VARCHAR); assert (metadata.getParameterTypeName(1).equalsIgnoreCase("varchar")); + assert (metadata.getParameterType(2) == java.sql.Types.DECIMAL); assert (metadata.getParameterTypeName(2).equalsIgnoreCase("decimal")); + assert (metadata.getParameterMode(1) == ParameterMetaData.parameterModeIn); assert (metadata.getPrecision(2) == 38); assert (metadata.getScale(2) == 5); + assert (!metadata.isSigned(1)); } } finally { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } + + /** + * Test MetaData for Stored procedure sp_help + * + * Stored Procedure reference: + * https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-help-transact-sql + * + * @throws SQLException + */ + @Test + public void testParameterMetaDataProc() throws SQLException { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { + String query = "exec sp_help (" + AbstractSQLGenerator.escapeIdentifier(tableName) + ")"; + + try (PreparedStatement pstmt = con.prepareStatement(query)) { + ParameterMetaData metadata = pstmt.getParameterMetaData(); + assert (metadata.getParameterCount() == 1); + assert (metadata.getParameterType(1) == java.sql.Types.NVARCHAR); + assert (metadata.getParameterTypeName(1).equalsIgnoreCase("nvarchar")); + assert (metadata.getParameterClassName(1).equalsIgnoreCase(String.class.getName())); + assert (metadata.getParameterMode(1) == ParameterMetaData.parameterModeIn); + // Standard value - validate precision of sp_help stored procedure parameter + assert (metadata.getPrecision(1) == 776); + assert (metadata.getScale(1) == 0); + assert (metadata.isNullable(1) == ParameterMetaData.parameterNullable); + assert (!metadata.isSigned(1)); + } + } + } } 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 387451b78..bfe9b1f62 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java @@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -37,14 +36,14 @@ public static void BeforeTests() throws SQLException { @AfterAll public static void dropTables() throws SQLException { - try (SQLServerConnection connection = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection connection = (SQLServerConnection) getConnection(); Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } private static void createCharTable() throws SQLException { - try (SQLServerConnection connection = (SQLServerConnection) DriverManager.getConnection(connectionString); + try (SQLServerConnection connection = (SQLServerConnection) getConnection(); Statement stmt = connection.createStatement()) { stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1 int)"); } 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 eeb0c604a..c9752f961 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java @@ -12,14 +12,12 @@ import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.Date; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; -import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; @@ -43,6 +41,8 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; import microsoft.sql.DateTimeOffset; @@ -68,12 +68,11 @@ private Object[] generateExpectedValues() { BigDecimal randomBigDecimal = new BigDecimal(ramdonNum); BigDecimal randomMoney = RandomData.generateMoney(false); BigDecimal randomSmallMoney = RandomData.generateSmallMoney(false); - // Temporal datatypes - Date randomDate = Date.valueOf(LocalDateTime.now().toLocalDate()); - Time randomTime = new Time(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); + Date randomDate = Date.valueOf(Constants.NOW.toLocalDate()); + Time randomTime = new Time(Constants.NOW.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); Timestamp randomTimestamp = new Timestamp( - LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); + Constants.NOW.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); // Datetime can only end in 0,3,7 and will be rounded to those numbers on the server. Manually set nanos Timestamp roundedDatetime = randomTimestamp; @@ -84,7 +83,7 @@ private Object[] generateExpectedValues() { smallTimestamp.setSeconds(0); Object[] expected = new Object[23]; - expected[0] = random.nextLong(); + expected[0] = Constants.RANDOM.nextLong(); expected[1] = randomBinary; expected[2] = true; expected[3] = randomChar; @@ -97,7 +96,7 @@ private Object[] generateExpectedValues() { expected[10] = ramdonNum; expected[11] = randomMoney; expected[12] = randomChar; - expected[13] = BigDecimal.valueOf(random.nextInt()); + expected[13] = BigDecimal.valueOf(Constants.RANDOM.nextInt()); expected[14] = randomString; expected[15] = randomFloat; expected[16] = smallTimestamp; @@ -113,7 +112,7 @@ private Object[] generateExpectedValues() { @Test public void testIsInsert() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { String valid1 = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " values (1, 2)"; String valid2 = " insert into " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " values (1, 2)"; @@ -132,7 +131,7 @@ public void testIsInsert() throws Exception { @Test public void testComments() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); PreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement("");) { String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " /*rando comment */" @@ -153,7 +152,7 @@ public void testComments() throws Exception { @Test public void testBrackets() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); PreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement("");) { String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ [BulkCopy[]]Table] /*rando comment */" + " /* rando comment */values/* rando comment */ (1, 2)"; @@ -172,7 +171,7 @@ public void testBrackets() throws Exception { @Test public void testDoubleQuotes() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); PreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement("");) { String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ \"Bulk\"\"\"\"Table\" /*rando comment */" + " /* rando comment */values/* rando comment */ (1, 2)"; @@ -192,7 +191,7 @@ public void testDoubleQuotes() throws Exception { @SuppressWarnings("unchecked") @Test public void testAll() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); PreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement("");) { String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ \"Bulk\"\"\"\"Table\" /*rando comment */" + " /* rando comment */ (\"c1\"/* rando comment */, /* rando comment */[c2]/* rando comment */, /* rando comment */ /* rando comment */c3/* rando comment */, c4)" @@ -230,7 +229,7 @@ public void testAllcolumns() throws Exception { + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?" + ")"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -285,7 +284,7 @@ public void testMixColumns() throws Exception { String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1, c3, c5, c8) values " + "(" + "?, " + "?, " + "?, " + "? " + ")"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -293,9 +292,9 @@ public void testMixColumns() throws Exception { f1.set(connection, true); Timestamp randomTimestamp = new Timestamp( - LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); - Date randomDate = Date.valueOf(LocalDateTime.now().toLocalDate()); - long randomLong = random.nextLong(); + Constants.NOW.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); + Date randomDate = Date.valueOf(Constants.NOW.toLocalDate()); + long randomLong = Constants.RANDOM.nextLong(); pstmt.setLong(1, randomLong); // bigint pstmt.setBoolean(2, true); // bit @@ -330,15 +329,14 @@ public void testNullOrEmptyColumns() throws Exception { String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1, c2, c3, c4, c5, c6, c7) values " + "(" + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "? " + ")"; - - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); f1.setAccessible(true); f1.set(connection, true); - long randomLong = random.nextLong(); + long randomLong = Constants.RANDOM.nextLong(); String randomChar = RandomData.generateCharTypes("1", false, false); pstmt.setLong(1, randomLong); // bigint @@ -379,7 +377,7 @@ public void testNullOrEmptyColumns() throws Exception { public void testSquareBracketAgainstDB() throws Exception { String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + " values (?)"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -409,7 +407,7 @@ public void testSquareBracketAgainstDB() throws Exception { public void testDoubleQuoteAgainstDB() throws Exception { String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName) + " values (?)"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -439,7 +437,7 @@ public void testDoubleQuoteAgainstDB() throws Exception { public void testSchemaAgainstDB() throws Exception { String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(schemaTableName) + " values (?)"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -469,7 +467,7 @@ public void testColumnNameMixAgainstDB() throws Exception { String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + " ([c]]]]1], [c]]]]2]) values (?, 1)"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -501,7 +499,7 @@ public void testAllColumnsLargeBatch() throws Exception { + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?" + ")"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -555,7 +553,7 @@ public void testAllColumnsLargeBatch() throws Exception { public void testIllegalNumberOfArgNoColumnList() throws Exception { String invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?, ?,? ,?) "; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -577,7 +575,7 @@ public void testIllegalNumberOfArgNoColumnList() throws Exception { invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1, c2, c3) values (?, ?,? ,?) "; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -606,7 +604,7 @@ public void testNonParameterizedQuery() throws Exception { String invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values ((SELECT * from table where c1=?), ?,? ,?) "; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); Statement stmt = (SQLServerStatement) connection.createStatement();) { @@ -632,7 +630,7 @@ public void testNonParameterizedQuery() throws Exception { invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values ('?', ?,? ,?) "; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); Statement stmt = (SQLServerStatement) connection.createStatement();) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -657,7 +655,7 @@ public void testNonSupportedColumns() throws Exception { String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(unsupportedTableName) + " values (?, ?, ?, ?)"; - try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); Statement stmt = (SQLServerStatement) connection.createStatement()) { Field f1 = SQLServerConnection.class.getDeclaredField("isAzureDW"); @@ -695,8 +693,7 @@ public void testNonSupportedColumns() throws Exception { @BeforeEach public void testSetup() throws TestAbortedException, Exception { - try (Connection connection = DriverManager - .getConnection(connectionString + ";useBulkCopyForBatchInsert=true;")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;")) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " " + "(" @@ -713,7 +710,7 @@ public void testSetup() throws TestAbortedException, Exception { @AfterAll public static void terminateVariation() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString)) { + try (Connection connection = PrepUtil.getConnection(connectionString)) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameBulk), 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 44b9508ee..005311584 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -29,6 +28,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -53,8 +53,7 @@ public void testAddBatch2() throws SQLException { int key = 42; // this is the minimum sequence, I've found to trigger the error\ - try (Connection conn = DriverManager.getConnection(connectionString); - PreparedStatement pstmt = conn.prepareStatement(sPrepStmt)) { + try (Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sPrepStmt)) { pstmt.setInt(1, key++); pstmt.setNull(2, Types.VARCHAR); pstmt.addBatch(); @@ -99,8 +98,7 @@ public void testAddBatch2() throws SQLException { */ @Test public void testAddbatch2AEOnConnection() throws SQLException { - try (Connection connection = DriverManager - .getConnection(connectionString + ";columnEncryptionSetting=Enabled;")) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";columnEncryptionSetting=Enabled;")) { testAddBatch2(); } } @@ -111,7 +109,7 @@ public void testSetup() throws TestAbortedException, Exception { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - try (Connection connection = DriverManager.getConnection(connectionString); + try (Connection connection = getConnection(); SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -124,8 +122,7 @@ public void testSetup() throws TestAbortedException, Exception { @AfterAll public static void terminateVariation() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { + try (Connection conn = getConnection(); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { 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 46a7a729f..8a0dee24c 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java @@ -9,7 +9,6 @@ import java.lang.reflect.Field; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -30,6 +29,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -51,7 +51,7 @@ public class RegressionTest extends AbstractTest { */ @BeforeAll public static void setupTest() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } @@ -64,7 +64,7 @@ public static void setupTest() throws SQLException { @Test @Tag("AzureDWTest") public void createViewTest() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement pstmt1 = con.prepareStatement( "create view " + AbstractSQLGenerator.escapeIdentifier(tableName) + " as select 1 a"); PreparedStatement pstmt2 = con @@ -85,7 +85,7 @@ public void createViewTest() throws SQLException { @Test @Tag("AzureDWTest") public void createSchemaTest() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement pstmt1 = con .prepareStatement("create schema " + AbstractSQLGenerator.escapeIdentifier(schemaName)); PreparedStatement pstmt2 = con @@ -106,7 +106,7 @@ public void createSchemaTest() throws SQLException { @Test @Tag("AzureDWTest") public void createTableTest() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement pstmt1 = con.prepareStatement( "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); PreparedStatement pstmt2 = con @@ -127,7 +127,7 @@ public void createTableTest() throws SQLException { @Test @Tag("AzureDWTest") public void alterTableTest() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement pstmt1 = con.prepareStatement( "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); PreparedStatement pstmt2 = con.prepareStatement( @@ -151,7 +151,7 @@ public void alterTableTest() throws SQLException { @Test @Tag("AzureDWTest") public void grantTest() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement pstmt1 = con.prepareStatement( "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); PreparedStatement pstmt2 = con.prepareStatement( @@ -186,7 +186,7 @@ public void batchWithLargeStringTestUseBulkCopyAPI() throws Exception { } private void batchWithLargeStringTestInternal(String mode) throws Exception { - try (Connection con = DriverManager.getConnection(connectionString);) { + try (Connection con = getConnection();) { if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI((SQLServerConnection) con); } @@ -209,7 +209,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { + " ( ID int, DATA nvarchar(max) );"); } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } con.commit(); @@ -252,15 +252,15 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { pstmt.executeBatch(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } con.commit(); // check the data in the table Map selectedValues = new LinkedHashMap<>(); int id = 0; - try (PreparedStatement pstmt = con - .prepareStatement("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName2) + ";")) { + try (PreparedStatement pstmt = con.prepareStatement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName2) + Constants.SEMI_COLON)) { try (ResultSet rs = pstmt.executeQuery()) { int i = 0; while (rs.next()) { @@ -287,7 +287,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { */ @Test public void addBatchWithLargeStringTest() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); con.setAutoCommit(false); @@ -305,7 +305,7 @@ public void addBatchWithLargeStringTest() throws SQLException { + " ( ID int, DATA nvarchar(max) );"); } } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } con.commit(); @@ -365,7 +365,7 @@ public void addBatchWithLargeStringTest() throws SQLException { } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } finally { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); } @@ -374,8 +374,8 @@ public void addBatchWithLargeStringTest() throws SQLException { @Test public void testQueryParamsWithHyphen() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement st1 = con.prepareStatement("SELECT 1 WHERE -1=-1 AND 1=?")){ + try (Connection con = getConnection(); + PreparedStatement st1 = con.prepareStatement("SELECT 1 WHERE -1=-1 AND 1=?")) { st1.setInt(1, 1); try (ResultSet rs = st1.executeQuery()) { while (rs.next()) @@ -386,8 +386,8 @@ public void testQueryParamsWithHyphen() throws Exception { @Test public void testQueryParamsWithComment() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement st1 = con.prepareStatement("/**COMMENT**/ SELECT 1 WHERE 1=?")){ + try (Connection con = getConnection(); + PreparedStatement st1 = con.prepareStatement("/**COMMENT**/ SELECT 1 WHERE 1=?")) { st1.setInt(1, 1); try (ResultSet rs = st1.executeQuery()) { while (rs.next()) @@ -398,8 +398,8 @@ public void testQueryParamsWithComment() throws Exception { @Test public void testQueryParamsWithLineComment() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement st1 = con.prepareStatement("--comment\nSELECT 1 WHERE 1=?")){ + try (Connection con = getConnection(); + PreparedStatement st1 = con.prepareStatement("--comment\nSELECT 1 WHERE 1=?")) { st1.setInt(1, 1); try (ResultSet rs = st1.executeQuery()) { while (rs.next()) @@ -410,8 +410,8 @@ public void testQueryParamsWithLineComment() throws Exception { @Test public void testQueryParamsWithBackSlash() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement st1 = con.prepareStatement("SELECT 1, '/''' AS str WHERE 1=?")){ + try (Connection con = getConnection(); + PreparedStatement st1 = con.prepareStatement("SELECT 1, '/''' AS str WHERE 1=?")) { st1.setInt(1, 1); try (ResultSet rs = st1.executeQuery()) { while (rs.next()) { @@ -421,7 +421,7 @@ public void testQueryParamsWithBackSlash() throws Exception { } } } - + /** * Cleanup after test * @@ -429,7 +429,7 @@ public void testQueryParamsWithBackSlash() throws Exception { */ @AfterAll public static void cleanup() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); 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/preparedStatement/SetObjectTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/SetObjectTest.java index 4d13267f8..0d5ef434e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/SetObjectTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/SetObjectTest.java @@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -37,7 +36,7 @@ public class SetObjectTest extends AbstractTest { */ @Test public void testSetObjectWithOffsetDateTime() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { final String testValue = "2018-01-02T11:22:33.123456700+12:34"; try (Statement stmt = con.createStatement()) { stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -70,7 +69,7 @@ public void testSetObjectWithOffsetDateTime() throws SQLException { */ @Test public void testSetObjectWithOffsetTime() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { final String testValue = "11:22:33.123456700+12:34"; final String expectedDto = "1970-01-01T" + testValue; try (Statement stmt = con.createStatement()) { @@ -104,7 +103,7 @@ public void testSetObjectWithOffsetTime() throws SQLException { */ @Test public void testSetObjectWithOffsetTime_sendTimeAsDatetimeDisabled() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { ((SQLServerConnection) con).setSendTimeAsDatetime(false); final String testValue = "11:22:33.123456700+12:34"; final String expectedDto = "1900-01-01T" + testValue; 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 098f789d5..2296941e0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java @@ -5,7 +5,6 @@ package com.microsoft.sqlserver.jdbc.resultset; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; @@ -34,8 +33,7 @@ public class DataClassificationTest extends AbstractTest { @Test public void testDataClassificationMetadata() throws Exception { // Run this test only with newer SQL Servers (version>=2018) that support Data Classification - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement();) { + try (Connection con = getConnection(); Statement stmt = connection.createStatement();) { if (TestUtils.serverSupportsDataClassification(stmt)) { createTable(connection, stmt); runTestsForServer(stmt); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java index 25366d6c1..bdfd7ac7b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java @@ -16,7 +16,6 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.NClob; import java.sql.ResultSet; import java.sql.SQLException; @@ -55,7 +54,7 @@ public class ResultSetTest extends AbstractTest { */ @Test public void testJdbc41ResultSetMethods() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { 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), " @@ -260,7 +259,7 @@ public void testJdbc41ResultSetMethods() throws SQLException { @Test @Tag("AzureDWTest") public void testGetObjectAsLocalDateTime() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { TimeZone prevTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("America/Edmonton")); @@ -303,7 +302,7 @@ public void testGetObjectAsLocalDateTime() throws SQLException { */ @Test public void testGetObjectAsOffsetDateTime() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { final String testValue = "2018-01-02T11:22:33.123456700+12:34"; stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -338,7 +337,7 @@ public void testGetObjectAsOffsetDateTime() throws SQLException { @Test @Tag("AzureDWTest") public void testResultSetWrapper() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int, col2 varchar(8000), col3 int identity(1,1))"); @@ -364,7 +363,7 @@ public void testResultSetWrapper() throws SQLException { @Test @Tag("AzureDWTest") public void testGetterOnNull() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select null")) { rs.next(); assertEquals(null, rs.getTime(1)); @@ -380,7 +379,7 @@ public void testGetterOnNull() throws SQLException { public void testGetSetHoldability() throws SQLException { int[] holdabilityOptions = {ResultSet.HOLD_CURSORS_OVER_COMMIT, ResultSet.CLOSE_CURSORS_AT_COMMIT}; - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select null")) { int connHold = con.getHoldability(); @@ -403,7 +402,7 @@ public void testGetSetHoldability() throws SQLException { */ @Test public void testResultSetMethods() throws SQLException { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -505,7 +504,7 @@ public void testResultSetMethods() throws SQLException { } while (rs.next()); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } finally { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/ssl/trustmanager/CustomTrustManagerTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/ssl/trustmanager/CustomTrustManagerTest.java index ba8c761ff..dc9371a8b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/ssl/trustmanager/CustomTrustManagerTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/ssl/trustmanager/CustomTrustManagerTest.java @@ -8,7 +8,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.sql.DriverManager; +import java.sql.Connection; import java.sql.SQLException; import org.junit.jupiter.api.Tag; @@ -18,6 +18,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -33,7 +34,7 @@ public class CustomTrustManagerTest extends AbstractTest { public void testWithPermissiveX509TrustManager() throws Exception { String url = connectionString + ";trustManagerClass=" + PermissiveTrustManager.class.getName() + ";encrypt=true;"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(url)) { + try (Connection con = PrepUtil.getConnection(url)) { assertTrue(con != null); } } @@ -47,7 +48,7 @@ public void testWithPermissiveX509TrustManager() throws Exception { public void testWithTrustManagerConstructorArg() throws Exception { String url = connectionString + ";trustManagerClass=" + TrustManagerWithConstructorArg.class.getName() + ";trustManagerConstructorArg=dummyString;" + ";encrypt=true;"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(url)) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(url)) { assertTrue(con != null); } } @@ -60,7 +61,7 @@ public void testWithTrustManagerConstructorArg() throws Exception { @Test public void testWithInvalidTrustManager() throws Exception { String url = connectionString + ";trustManagerClass=" + InvalidTrustManager.class.getName() + ";encrypt=true;"; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(url)) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(url)) { fail(); } catch (SQLException e) { assertTrue(e.getMessage().contains( diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypesTest.java index a2124deb8..4d3eeb0f6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypesTest.java @@ -7,7 +7,6 @@ import static org.junit.Assert.fail; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -28,6 +27,7 @@ import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; +import com.microsoft.sqlserver.testframework.PrepUtil; import com.microsoft.sqlserver.testframework.sqlType.SqlType; @@ -66,7 +66,7 @@ private void testTVPResultSet(boolean setSelectMethod, Integer resultSetType, connString = connectionString; } - try (Connection conn = DriverManager.getConnection(connString)) { + try (Connection conn = PrepUtil.getConnection(connString)) { if (null != resultSetType && null != resultSetConcurrency) { stmt = conn.createStatement(resultSetType, resultSetConcurrency); } else { @@ -79,10 +79,9 @@ private void testTVPResultSet(boolean setSelectMethod, Integer resultSetType, "INSERT INTO " + tableDest.getEscapedTableName() + " select * from ? ;")) { pstmt.setStructured(1, tvpName, rs); pstmt.execute(); - ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(conn), tableSrc, - tableDest); + ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(conn), tableSrc, tableDest); } catch (Exception e) { - fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); + fail(TestResource.getResource("R_unexpectedErrorMessage") + e.getMessage()); } finally { stmt.close(); } @@ -117,7 +116,7 @@ private void testTVPStoredProcedureResultSet(boolean setSelectMethod, Integer re connString = connectionString; } - try (Connection conn = DriverManager.getConnection(connString)) { + try (Connection conn = PrepUtil.getConnection(connString)) { if (null != resultSetType && null != resultSetConcurrency) { stmt = conn.createStatement(resultSetType, resultSetConcurrency); } else { @@ -130,8 +129,7 @@ private void testTVPStoredProcedureResultSet(boolean setSelectMethod, Integer re .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}")) { Cstmt.setStructured(1, tvpName, rs); Cstmt.execute(); - ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(conn), tableSrc, - tableDest); + ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(conn), tableSrc, tableDest); } finally { stmt.close(); } @@ -148,7 +146,7 @@ private void testTVPStoredProcedureResultSet(boolean setSelectMethod, Integer re @Test public void testTVPDataTable() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { setupVariation(false, stmt); SQLServerDataTable dt = new SQLServerDataTable(); int numberOfColumns = tableDest.getColumns().size(); @@ -214,7 +212,7 @@ private void setupVariation(boolean setSelectMethod, Statement stmt) throws SQLE } private void terminateVariation() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); TestUtils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); TestUtils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java index badc77b11..a1a1cf57e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java @@ -9,7 +9,6 @@ import java.io.IOException; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -81,7 +80,7 @@ public void testExceptionWithInvalidStoredProcedureName() throws Exception { } catch (Exception e) { if (e instanceof SQLException) { assertTrue(e.getMessage().contains(TestResource.getResource("R_StoredProcedureNotFound")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); + TestResource.getResource("R_invalidErrorMessage") + e.getMessage()); } else { throw e; } @@ -96,8 +95,7 @@ public void testExceptionWithInvalidStoredProcedureName() throws Exception { */ @Test public void tryTVPPrecisionmissedissue315() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement(); + try (Connection connection = getConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6)); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection @@ -130,8 +128,7 @@ private void testTime6DestTable() throws SQLException, IOException { @BeforeAll public static void beforeAll() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { dropProcedure(); @@ -191,8 +188,7 @@ private static void populateCharSrcTable() throws SQLException { } private static void populateTime6SrcTable() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6) + " values ('2017-05-12 " + expectedTime6value + "')"; connection.createStatement().execute(sql); @@ -200,15 +196,13 @@ private static void populateTime6SrcTable() throws SQLException { } private static void dropProcedure() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(spName_varcharMax), stmt); } } private static void createProcedure() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); 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) @@ -221,8 +215,7 @@ private static void createProcedure() throws SQLException { @AfterAll public static void terminateVariation() throws SQLException { dropProcedure(); - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); 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)); 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 49dafa04d..57d261507 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java @@ -5,7 +5,6 @@ package com.microsoft.sqlserver.jdbc.tvp; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.Statement; @@ -73,7 +72,7 @@ public void testSetup() throws SQLException { } private void dropProcedure() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); 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); @@ -82,14 +81,14 @@ private void dropProcedure() throws SQLException { } private static void dropTables() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); 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 { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); 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)); @@ -100,14 +99,14 @@ private static void createPreocedure() throws SQLException { 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()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.execute(sql); } } private void createTables() throws SQLException { String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (c1 numeric(6,3) null);"; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.execute(sql); } } @@ -115,7 +114,7 @@ private void createTables() throws SQLException { private void createTVPS() throws SQLException { String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 numeric(6,3) null)"; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.executeUpdate(TVPCreateCmd); } } 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 a21dd332b..37ad348f8 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java @@ -8,7 +8,6 @@ import java.math.BigDecimal; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -29,6 +28,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -64,7 +64,7 @@ public void testServerCursors() throws SQLException { } private void serverCursorsTest(int resultSetType, int resultSetConcurrency) throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { dropTVPS(); dropTables(); @@ -74,8 +74,8 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro populateSourceTable(); - try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency) - .executeQuery("select c1,c2,c3,c4 from " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " ORDER BY id ASC"); + try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency).executeQuery( + "select c1,c2,c3,c4 from " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " ORDER BY id ASC"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); @@ -96,7 +96,7 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro public void testSelectMethodSetToCursor() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - try (Connection conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = PrepUtil.getConnection(connectionString, info); Statement stmt = conn.createStatement()) { dropTVPS(); @@ -129,7 +129,7 @@ public void testSelectMethodSetToCursor() throws SQLException { public void testSelectMethodSetToCursorWithSP() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - try (Connection conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = PrepUtil.getConnection(connectionString, info); Statement stmt = conn.createStatement()) { dropProcedure(); @@ -166,7 +166,7 @@ public void testSelectMethodSetToCursorWithSP() throws SQLException { public void testInvalidTVPName() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - try (Connection conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = PrepUtil.getConnection(connectionString, info); Statement stmt = conn.createStatement()) { dropTVPS(); @@ -203,7 +203,7 @@ public void testInvalidTVPName() throws SQLException { public void testInvalidStoredProcedureName() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - try (Connection conn = DriverManager.getConnection(connectionString, info); + try (Connection conn = PrepUtil.getConnection(connectionString, info); Statement stmt = conn.createStatement()) { dropProcedure(); @@ -241,7 +241,7 @@ public void testInvalidStoredProcedureName() throws SQLException { */ @Test public void testMultiplePreparedStatementAndResultSet() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { dropTVPS(); dropTables(); @@ -308,7 +308,7 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { } private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = conn.createStatement().executeQuery("select c1,c2,c3,c4 from " + AbstractSQLGenerator.escapeIdentifier(desTable) + " ORDER BY id ASC;")) { @@ -336,7 +336,7 @@ private static void populateSourceTable() throws SQLException { Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { for (int i = 0; i < expectedBigDecimals.length; i++) { @@ -350,14 +350,14 @@ private static void populateSourceTable() throws SQLException { } private static void dropTables() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { 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()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000), id int not null identity);"; stmt.execute(sql); @@ -369,7 +369,7 @@ private static void createTables() throws SQLException { } private static void createTVPS() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { 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); @@ -377,7 +377,7 @@ private static void createTVPS() throws SQLException { } private static void dropTVPS() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.execute("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + AbstractSQLGenerator.escapeIdentifier(tvpName)); @@ -385,17 +385,17 @@ private static void dropTVPS() throws SQLException { } private static void dropProcedure() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); } } private static void createProcedure() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + "(c1,c2,c3,c4) SELECT * FROM @InputData ORDER BY c1 ASC" - + " END"; + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + + "(c1,c2,c3,c4) SELECT * FROM @InputData ORDER BY c1 ASC" + " END"; stmt.execute(sql); } 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 d3165489e..a4bf77ba9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -53,7 +52,7 @@ public void testTVPSchemaPreparedStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + try (Connection conn = getConnection(); 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); @@ -75,7 +74,7 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + try (Connection conn = getConnection(); 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); @@ -95,7 +94,7 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException @DisplayName("TVPSchemaPreparedInsertCommand") public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); SQLServerPreparedStatement P_C_stmt = (SQLServerPreparedStatement) conn .prepareStatement("INSERT INTO " + charTable + " select * from ? ;"); ResultSet rs = stmt.executeQuery("select * from " + charTable)) { @@ -116,7 +115,7 @@ public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOExceptio @DisplayName("TVPSchemaCallableInsertCommand()") public void testTVPSchemaCallableInsertCommand() throws SQLException, IOException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); SQLServerCallableStatement P_C_stmt = (SQLServerCallableStatement) conn .prepareCall("INSERT INTO " + charTable + " select * from ? ;"); ResultSet rs = stmt.executeQuery("select * from " + charTable)) { @@ -178,27 +177,27 @@ private void dropProcedure() throws SQLException { + TestUtils.escapeSingleQuotes(procedureName) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + procedureName; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.execute(sql); } } private static void dropTables() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); 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 { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); 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 { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.execute( "if EXISTS (SELECT * FROM sys.schemas where name = '" + TestUtils.escapeSingleQuotes(schemaName) + "') drop schema " + AbstractSQLGenerator.escapeIdentifier(schemaName)); @@ -210,7 +209,7 @@ private static void createPreocedure() throws SQLException { String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpNameWithSchema + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + charTable + " SELECT * FROM @InputData" + " END"; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.execute(sql); } } @@ -218,7 +217,7 @@ private static void createPreocedure() throws SQLException { private void createTables() throws SQLException { String sql = "create table " + charTable + " (" + "PlainChar char(50) null," + "PlainVarchar varchar(50) null," + "PlainVarcharMax varchar(max) null," + ");"; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.execute(sql); } } @@ -226,7 +225,7 @@ private void createTables() throws SQLException { private void createTVPS() throws SQLException { String TVPCreateCmd = "CREATE TYPE " + tvpNameWithSchema + " as table ( " + "PlainChar char(50) null," + "PlainVarchar varchar(50) null," + "PlainVarcharMax varchar(max) null" + ")"; - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.executeUpdate(TVPCreateCmd); } } 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 d48f3bb57..de8440918 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -65,9 +64,8 @@ public void testLongVarchar() throws SQLException { pstmt.execute(); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -100,9 +98,8 @@ public void testLongNVarchar() throws SQLException { pstmt.execute(); - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(); ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -133,9 +130,8 @@ public void testXML() throws SQLException { pstmt.execute(); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -165,9 +161,8 @@ public void testnText() throws SQLException { pstmt.execute(); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -197,9 +192,8 @@ public void testText() throws SQLException { pstmt.execute(); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -229,9 +223,8 @@ public void testImage() throws SQLException { pstmt.execute(); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertTrue(parseByte(rs.getBytes(1), value.getBytes())); @@ -265,9 +258,8 @@ public void testTVPLongVarcharStoredProcedure() throws SQLException { 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 " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -299,9 +291,8 @@ public void testTVPLongNVarcharStoredProcedure() throws SQLException { 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 " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -333,9 +324,8 @@ public void testTVPXMLStoredProcedure() throws SQLException { 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 " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -368,9 +358,8 @@ public void testTVPTextStoredProcedure() throws SQLException { 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 " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -403,9 +392,8 @@ public void testTVPNTextStoredProcedure() throws SQLException { 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 " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -438,9 +426,8 @@ public void testTVPImageStoredProcedure() throws SQLException { 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 " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertTrue(parseByte(rs.getBytes(1), value.getBytes())); } @@ -469,9 +456,8 @@ public void testDateTime() throws SQLException { pstmt.execute(); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(((SQLServerResultSet) rs).getDateTime(1), value); } @@ -502,9 +488,8 @@ public void testSmallDateTime() throws SQLException { pstmt.execute(); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt - .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + try (Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(((SQLServerResultSet) rs).getSmallDateTime(1), returnValue); } @@ -518,7 +503,7 @@ public void testSetup() throws SQLException { tableName = RandomUtil.getIdentifier("TVPTable"); procedureName = RandomUtil.getIdentifier("procedureThatCallsTVP"); - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { dropProcedure(); dropTables(); dropTVPS(); @@ -527,7 +512,7 @@ public void testSetup() throws SQLException { @AfterAll public static void terminate() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { dropProcedure(); dropTables(); dropTVPS(); @@ -535,7 +520,7 @@ public static void terminate() throws SQLException { } private static void dropProcedure() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); 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); @@ -544,14 +529,14 @@ private static void dropProcedure() throws SQLException { } private static void dropTables() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { 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()) { + try (Connection conn = getConnection(); 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)); @@ -559,7 +544,7 @@ private static void dropTVPS() throws SQLException { } private static void createPreocedure() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SELECT * FROM @InputData" @@ -569,7 +554,7 @@ private static void createPreocedure() throws SQLException { } private void createTables(String colType) throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1 " + colType + " null);"; stmt.execute(sql); @@ -577,7 +562,7 @@ private void createTables(String colType) throws SQLException { } private void createTVPS(String colType) throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 " + colType + " null)"; stmt.executeUpdate(TVPCreateCmd); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/SavepointTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/SavepointTest.java index aea5689d3..22b7c2056 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/SavepointTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/SavepointTest.java @@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.text.MessageFormat; @@ -36,14 +35,14 @@ public class SavepointTest extends AbstractTest { */ @Test public void testSavePointName() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString)) { + try (Connection connection = getConnection()) { connection.setAutoCommit(false); SQLServerSavepoint savePoint = (SQLServerSavepoint) connection.setSavepoint(savePointName); MessageFormat form = new MessageFormat(TestResource.getResource("R_savePointError")); Object[][] msgArgs = {{"Name", "same"}, {"Label", "Savepoint Name"}, - {"SQLServerSavepoint.isNamed", "true"}}; + {"SQLServerSavepoint.isNamed", Boolean.TRUE.toString()}}; assertTrue(savePointName.equals(savePoint.getSavepointName()), form.format(msgArgs[0])); assertTrue(savePointName.equals(savePoint.getLabel()), form.format(msgArgs[1])); @@ -65,7 +64,7 @@ public void testSavePointName() throws SQLException { */ @Test public void testSavePointId() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString)) { + try (Connection connection = getConnection()) { connection.setAutoCommit(false); @@ -94,7 +93,7 @@ public void testSavePointId() throws SQLException { */ @Test public void testSavePointIsNamed() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString)) { + try (Connection connection = getConnection()) { connection.setAutoCommit(false); @@ -114,7 +113,7 @@ public void testSavePointIsNamed() throws SQLException { */ @Test public void testSavePointWithAutoCommit() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString)) { + try (Connection connection = getConnection()) { connection.setAutoCommit(true); 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 25f7e1c9d..f401eae45 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 @@ -7,14 +7,12 @@ import java.io.Reader; import java.sql.Clob; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; -import java.util.Random; import java.util.stream.IntStream; import org.junit.jupiter.api.BeforeEach; @@ -27,24 +25,14 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; @RunWith(JUnitPlatform.class) public class LobsStreamingTest extends AbstractTest { - private static final int LOB_ARRAY_SIZE = 500; // number of rows to insert into the table and compare - private static final int LOB_LENGTH_MIN = 8000; - private static final int LOB_LENGTH_MAX = 32000; - private static final String ASCII_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+,./;'[]<>?:{}|`~\"\\"; - private static final String UNICODE_CHARACTERS = ASCII_CHARACTERS - + "Ǥ⚌c♮ƺåYèĢù⚏Ȓ★njäõpƸŃōoƝĤßuÙőƆE♹gLJÜŬȺDZ!Û☵ŦãǁĸNQŰǚǻTÖC]ǶýåÉbɉ☩=\\ȍáźŗǃĻýű☓☄¸T☑ö^k☏I:x☑⚀läiȉ☱☚⚅ǸǎãÂ"; private static String tableName = null; - private static enum Lob { - CLOB, - NCLOB - }; - @BeforeEach public void init() throws SQLException { tableName = RandomUtil.getIdentifier("streamingTest"); @@ -52,9 +40,8 @@ public void init() throws SQLException { private String getRandomString(int length, String validCharacters) { StringBuilder salt = new StringBuilder(); - Random rnd = new Random(); while (salt.length() < length) { - int index = (int) (rnd.nextFloat() * validCharacters.length()); + int index = (int) (Constants.RANDOM.nextFloat() * validCharacters.length()); salt.append(validCharacters.charAt(index)); } String saltStr = salt.toString(); @@ -79,17 +66,17 @@ private String getStringFromReader(Reader r, long l) throws IOException { return stringBuilder.toString(); } - private void createLobTable(Statement stmt, String table, Lob l) throws SQLException { - String columnType = (l == Lob.CLOB) ? "varchar(max)" : "nvarchar(max)"; + private void createLobTable(Statement stmt, String table, Constants.LOB l) throws SQLException { + String columnType = (l == Constants.LOB.CLOB) ? "varchar(max)" : "nvarchar(max)"; stmt.execute("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table) + " (id int, lobValue " + columnType + ")"); } - private ArrayList createRandomStringArray(Lob l) { - String characterPool = (l == Lob.CLOB) ? ASCII_CHARACTERS : UNICODE_CHARACTERS; + private ArrayList createRandomStringArray(Constants.LOB l) { + String characterPool = (l == Constants.LOB.CLOB) ? Constants.ASCII_CHARACTERS : Constants.UNICODE_CHARACTERS; ArrayList string_array = new ArrayList<>(); - IntStream.range(0, LOB_ARRAY_SIZE).forEach(i -> string_array.add( - getRandomString(random.nextInt(LOB_LENGTH_MIN, LOB_LENGTH_MAX), characterPool))); + IntStream.range(0, Constants.LOB_ARRAY_SIZE).forEach(i -> string_array.add(getRandomString( + Constants.RANDOM.nextInt(Constants.LOB_LENGTH_MIN, Constants.LOB_LENGTH_MAX), characterPool))); return string_array; } @@ -109,11 +96,11 @@ private void insertData(Connection conn, String table, ArrayList lobs) t @Test @DisplayName("testLengthAfterStream") public void testLengthAfterStream() throws SQLException, IOException { - try (Connection conn = DriverManager.getConnection(connectionString);) { + try (Connection conn = getConnection();) { try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - createLobTable(stmt, tableName, Lob.CLOB); - ArrayList lob_data = createRandomStringArray(Lob.CLOB); + createLobTable(stmt, tableName, Constants.LOB.CLOB); + ArrayList lob_data = createRandomStringArray(Constants.LOB.CLOB); insertData(conn, tableName, lob_data); try (ResultSet rs = stmt.executeQuery("SELECT * FROM [" + tableName + "] ORDER BY id ASC")) { @@ -137,11 +124,11 @@ public void testLengthAfterStream() throws SQLException, IOException { @Test @DisplayName("testClobsVarcharASCII") public void testClobsVarcharASCII() throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - createLobTable(stmt, tableName, Lob.CLOB); - ArrayList lob_data = createRandomStringArray(Lob.CLOB); + createLobTable(stmt, tableName, Constants.LOB.CLOB); + ArrayList lob_data = createRandomStringArray(Constants.LOB.CLOB); insertData(conn, tableName, lob_data); ArrayList lobsFromServer = new ArrayList<>(); @@ -174,12 +161,12 @@ public void testClobsVarcharASCII() throws SQLException { @Test @DisplayName("testNClobsNVarcharASCII") public void testNClobsVarcharASCII() throws SQLException, IOException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - createLobTable(stmt, tableName, Lob.NCLOB); + createLobTable(stmt, tableName, Constants.LOB.NCLOB); // Testing AsciiStream, use Clob string set or characters will be converted to '?' - ArrayList lob_data = createRandomStringArray(Lob.CLOB); + ArrayList lob_data = createRandomStringArray(Constants.LOB.CLOB); insertData(conn, tableName, lob_data); try (ResultSet rs = stmt.executeQuery("SELECT * FROM [" + tableName + "] ORDER BY id ASC")) { @@ -204,11 +191,11 @@ public void testNClobsVarcharASCII() throws SQLException, IOException { @Test @DisplayName("testClobsVarcharCHARA") public void testClobsVarcharCHARA() throws SQLException, IOException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - createLobTable(stmt, tableName, Lob.CLOB); - ArrayList lob_data = createRandomStringArray(Lob.CLOB); + createLobTable(stmt, tableName, Constants.LOB.CLOB); + ArrayList lob_data = createRandomStringArray(Constants.LOB.CLOB); insertData(conn, tableName, lob_data); ArrayList lobsFromServer = new ArrayList<>(); @@ -241,11 +228,11 @@ public void testClobsVarcharCHARA() throws SQLException, IOException { @Test @DisplayName("testNClobsVarcharCHARA") public void testNClobsVarcharCHARA() throws SQLException, IOException { - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { try (Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - createLobTable(stmt, tableName, Lob.NCLOB); - ArrayList lob_data = createRandomStringArray(Lob.NCLOB); + createLobTable(stmt, tableName, Constants.LOB.NCLOB); + ArrayList lob_data = createRandomStringArray(Constants.LOB.NCLOB); insertData(conn, tableName, lob_data); ArrayList lobsFromServer = new ArrayList<>(); 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 98791a22b..dce17c67b 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 @@ -14,7 +14,6 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -26,7 +25,6 @@ import java.util.List; import java.util.logging.Logger; -import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DynamicTest; @@ -43,9 +41,10 @@ import com.microsoft.sqlserver.jdbc.TestUtils.DBCharacterStream; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.DBCoercion; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.DBColumn; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.DBConstants; import com.microsoft.sqlserver.testframework.DBInvalidUtil; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBStatement; @@ -59,8 +58,6 @@ */ @RunWith(JUnitPlatform.class) public class LobsTest extends AbstractTest { - static Connection conn = null; - static Statement stmt = null; static String tableName; static String escapedTableName; int datasize; @@ -72,27 +69,12 @@ public class LobsTest extends AbstractTest { boolean isResultSet = false; DBTable table = null; - private static final int clobType = 0; - private static final int nClobType = 1; - private static final int blobType = 2; - @BeforeAll public static void init() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - tableName = RandomUtil.getIdentifier("LOBS"); escapedTableName = AbstractSQLGenerator.escapeIdentifier(tableName); } - @AfterAll - public static void terminate() throws SQLException { - if (null != conn) - conn.close(); - if (null != stmt) - stmt.close(); - } - @TestFactory public Collection executeDynamicTests() { List> classes = new ArrayList>( @@ -108,6 +90,7 @@ public Collection executeDynamicTests() { @Override public void execute() throws Throwable { testInvalidLobs(lobClass, isResultSet); + testFreedBlobs(lobClass, isResultSet); } }; // create a test display name @@ -132,151 +115,150 @@ public void execute() throws Throwable { private void testInvalidLobs(Class lobClass, boolean isResultSet) throws SQLException { String clobTypes[] = {"varchar(max)", "nvarchar(max)"}; String blobTypes[] = {"varbinary(max)"}; - int choose = random.nextInt(3); + int choose = Constants.RANDOM.nextInt(3); switch (choose) { case 0: datasize = packetSize; break; case 1: - datasize = packetSize + random.nextInt(packetSize) + 1; + datasize = packetSize + Constants.RANDOM.nextInt(packetSize) + 1; break; default: - datasize = packetSize - random.nextInt(packetSize); + datasize = packetSize - Constants.RANDOM.nextInt(packetSize); } - int coercionType = isResultSet ? DBCoercion.UPDATE : DBCoercion.SET; + int coercionType = isResultSet ? DBConstants.UPDATE_COERCION : DBConstants.SET_COERCION; Object updater = null; - Statement stmt = null; - try { - if (clobType == classType(lobClass) || nClobType == classType(lobClass)) { - table = createTable(table, clobTypes, true); - } else { - table = createTable(table, blobTypes, true); - } - for (int i = 0; i < table.getColumns().size(); i++) { - DBColumn col = table.getColumns().get(i); - try (DBConnection conn = new DBConnection(connectionString)) { - if (!col.getSqlType().canConvert(lobClass, coercionType, conn)) - continue; + try (Connection conn = getConnection(); Statement stmt1 = conn.createStatement()) { + try { + Statement stmt = null; + if (Constants.LOB.CLOB == classType(lobClass) || Constants.LOB.NCLOB == classType(lobClass)) { + table = createTable(table, clobTypes, true); + } else { + table = createTable(table, blobTypes, true); } - // re-create LOB since it might get closed - Object lob = this.createLob(lobClass); - if (isResultSet) { - stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - updater = stmt.executeQuery("Select " + table.getEscapedTableName() + ".[" + col.getColumnName() - + "]" + " from " + table.getEscapedTableName()); - ((ResultSet) updater).next(); - } else - updater = conn.prepareStatement("update " + table.getEscapedTableName() + " set " + ".[" - + col.getColumnName() + "]" + "=?"); - try { - this.updateLob(lob, updater, 1); - } catch (SQLException e) { - boolean verified = false; - - if (lobClass == Clob.class) - streamLength = ((DBInvalidUtil.InvalidClob) lob).length; - else if (lobClass == Blob.class) - streamLength = ((DBInvalidUtil.InvalidBlob) lob).length; - - // Case 1: Invalid length value is passed as LOB length - if (streamLength < 0 || streamLength == Long.MAX_VALUE) { - // Applies to all LOB types ("The length {0} is not valid} - assertTrue(e.getMessage().startsWith("The length"), - TestResource.getResource("R_unexpectedExceptionContent") + ": " + e.getMessage()); - assertTrue(e.getMessage().endsWith("is not valid."), - TestResource.getResource("R_unexpectedExceptionContent") + ": " + e.getMessage()); - verified = true; - + for (int i = 0; i < table.getColumns().size(); i++) { + DBColumn col = table.getColumns().get(i); + try (DBConnection dbConn = new DBConnection(connectionString)) { + if (!col.getSqlType().canConvert(lobClass, coercionType, dbConn)) + continue; + } + // re-create LOB since it might get closed + Object lob = this.createLob(lobClass); + if (isResultSet) { + stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + updater = stmt.executeQuery("Select " + table.getEscapedTableName() + ".[" + col.getColumnName() + + "]" + " from " + table.getEscapedTableName()); + ((ResultSet) updater).next(); + } else { + updater = conn.prepareStatement("update " + table.getEscapedTableName() + " set " + ".[" + + col.getColumnName() + "]" + "=?"); } + try { + this.updateLob(lob, updater, 1); + } catch (SQLException e) { + boolean verified = false; + + if (lobClass == Clob.class) + streamLength = ((DBInvalidUtil.InvalidClob) lob).length; + else if (lobClass == Blob.class) + streamLength = ((DBInvalidUtil.InvalidBlob) lob).length; + + // Case 1: Invalid length value is passed as LOB length + if (streamLength < 0 || streamLength == Long.MAX_VALUE) { + // Applies to all LOB types ("The length {0} is not valid} + assertTrue(e.getMessage().startsWith("The length"), + TestResource.getResource("R_unexpectedExceptionContent") + ": " + e.getMessage()); + assertTrue(e.getMessage().endsWith("is not valid."), + TestResource.getResource("R_unexpectedExceptionContent") + ": " + e.getMessage()); + verified = true; - // Case 2: CharacterStream or Clob.getCharacterStream threw IOException - if (lobClass == DBCharacterStream.class - || (lobClass == Clob.class && ((DBInvalidUtil.InvalidClob) lob).stream != null)) { - try (DBInvalidUtil.InvalidCharacterStream stream = lobClass == DBCharacterStream.class ? ((DBInvalidUtil.InvalidCharacterStream) lob) - : ((DBInvalidUtil.InvalidClob) lob).stream) { - if (stream.threwException) { - // CharacterStream threw IOException - String[] args = { - "java.io.IOException: " + DBInvalidUtil.InvalidCharacterStream.IOExceptionMsg}; - assertTrue(e.getMessage().contains(args[0])); - verified = true; - } } - } - if (!verified) { - // Odd CharacterStream length will throw this exception - if (!e.getMessage().contains(TestResource.getResource("R_badStreamLength"))) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_streamReadError"))); + + // Case 2: CharacterStream or Clob.getCharacterStream threw IOException + if (lobClass == DBCharacterStream.class + || (lobClass == Clob.class && ((DBInvalidUtil.InvalidClob) lob).stream != null)) { + try (DBInvalidUtil.InvalidCharacterStream stream = lobClass == DBCharacterStream.class ? ((DBInvalidUtil.InvalidCharacterStream) lob) + : ((DBInvalidUtil.InvalidClob) lob).stream) { + if (stream.threwException) { + // CharacterStream threw IOException + String[] args = {"java.io.IOException: " + + DBInvalidUtil.InvalidCharacterStream.IOExceptionMsg}; + assertTrue(e.getMessage().contains(args[0])); + verified = true; + } + } } + if (!verified) { + // Odd CharacterStream length will throw this exception + if (!e.getMessage().contains(TestResource.getResource("R_badStreamLength"))) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_streamReadError"))); + } + } } } - } - } catch (Exception e) { - dropTables(table); - e.printStackTrace(); - } finally { - dropTables(table); - if (null != updater) { - if (isResultSet) { - ((ResultSet) updater).close(); - } else { - ((PreparedStatement) updater).close(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + dropTables(table, stmt1); + if (null != updater) { + if (isResultSet) { + ((ResultSet) updater).close(); + } else { + ((PreparedStatement) updater).close(); + } } } - if (null != stmt) { - stmt.close(); - } } } - @Test - @DisplayName("testFreedBlobs") private void testFreedBlobs(Class lobClass, boolean isResultSet) throws SQLException { String types[] = {"varbinary(max)"}; - try { - table = createTable(table, types, false); // create empty table - int size = 10000; + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { + try { + table = createTable(table, types, false); // create empty table + int size = 10000; - byte[] data = new byte[size]; - random.nextBytes(data); + byte[] data = new byte[size]; + Constants.RANDOM.nextBytes(data); - Blob blob = null; - for (int i = 0; i < 5; i++) { - try (PreparedStatement ps = conn - .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { - blob = conn.createBlob(); - blob.setBytes(1, data); - ps.setInt(1, i + 1); - ps.setBlob(2, blob); - ps.executeUpdate(); + Blob blob = null; + for (int i = 0; i < 5; i++) { + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + blob = conn.createBlob(); + blob.setBytes(1, data); + ps.setInt(1, i + 1); + ps.setBlob(2, blob); + ps.executeUpdate(); + } } - } - try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { - for (int i = 0; i < 5; i++) { - rs.next(); + try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { + for (int i = 0; i < 5; i++) { + rs.next(); - blob = rs.getBlob(2); - try (InputStream stream = blob.getBinaryStream()) { - while (stream.available() > 0) - stream.read(); - blob.free(); - } - try (InputStream stream = blob.getBinaryStream()) {} catch (SQLException e) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); + blob = rs.getBlob(2); + try (InputStream stream = blob.getBinaryStream()) { + while (stream.available() > 0) + stream.read(); + blob.free(); + } + try (InputStream stream = blob.getBinaryStream()) {} catch (SQLException e) { + System.err.println(e.getMessage()); + assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); + } } } + try (InputStream stream = blob.getBinaryStream()) {} catch (SQLException e) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + dropTables(table, stmt); } - try (InputStream stream = blob.getBinaryStream()) {} catch (SQLException e) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_blobFreed"))); - } - } catch (Exception e) { - dropTables(table); - e.printStackTrace(); - } finally { - dropTables(table); } } @@ -314,7 +296,7 @@ private void testMultipleClose(Class streamClass) throws Exception { } else { DBColumn col = table.getColumns().get(i); try (DBConnection con = new DBConnection(connectionString)) { - if (!col.getSqlType().canConvert(streamClass, DBCoercion.GET, con)) + if (!col.getSqlType().canConvert(streamClass, DBConstants.GET_COERCION, con)) continue; } @@ -338,8 +320,10 @@ private void testMultipleClose(Class streamClass) throws Exception { } } } finally { - if (null != table) { - dropTables(table); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { + if (null != table) { + dropTables(table, stmt); + } } } } @@ -385,79 +369,78 @@ private void testLobsInsertRetrieve(String types[], Class lobClass) throws Ex int size = 10000; byte[] data = new byte[size]; - random.nextBytes(data); + Constants.RANDOM.nextBytes(data); Clob clob = null; Blob blob = null; NClob nclob = null; - try (PreparedStatement ps = conn - .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { - if (clobType == classType(lobClass)) { - String stringData = new String(data); - size = stringData.length(); - clob = conn.createClob(); - clob.setString(1, stringData); - ps.setInt(1, 1); - ps.setClob(2, clob); - } else if (nClobType == classType(lobClass)) { - String stringData = new String(data); - size = stringData.length(); - nclob = conn.createNClob(); - nclob.setString(1, stringData); - ps.setInt(1, 1); - ps.setNClob(2, nclob); - } - - else { - blob = conn.createBlob(); - blob.setBytes(1, data); - ps.setInt(1, 1); - ps.setBlob(2, blob); - } - ps.executeUpdate(); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + if (Constants.LOB.CLOB == classType(lobClass)) { + String stringData = new String(data); + size = stringData.length(); + clob = conn.createClob(); + clob.setString(1, stringData); + ps.setInt(1, 1); + ps.setClob(2, clob); + } else if (Constants.LOB.NCLOB == classType(lobClass)) { + String stringData = new String(data); + size = stringData.length(); + nclob = conn.createNClob(); + nclob.setString(1, stringData); + ps.setInt(1, 1); + ps.setNClob(2, nclob); + } else { + blob = conn.createBlob(); + blob.setBytes(1, data); + ps.setInt(1, 1); + ps.setBlob(2, blob); + } + ps.executeUpdate(); - byte[] chunk = new byte[size]; - try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { - while (rs.next()) { - if (clobType == classType(lobClass)) { - String stringData = new String(data); - size = stringData.length(); - clob = conn.createClob(); - clob.setString(1, stringData); - rs.getClob(2); - try (InputStream stream = clob.getAsciiStream()) { - assertEquals(clob.length(), size); - } + byte[] chunk = new byte[size]; + try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { + while (rs.next()) { + if (Constants.LOB.CLOB == classType(lobClass)) { + String stringData = new String(data); + size = stringData.length(); + clob = conn.createClob(); + clob.setString(1, stringData); + rs.getClob(2); + try (InputStream stream = clob.getAsciiStream()) { + assertEquals(clob.length(), size); + } - } else if (nClobType == classType(lobClass)) { - nclob = rs.getNClob(2); - assertEquals(nclob.length(), size); - try (InputStream stream = nclob.getAsciiStream(); - BufferedInputStream is = new BufferedInputStream(stream)) { - is.read(chunk); - assertEquals(chunk.length, size); - } - } else { - blob = rs.getBlob(2); - try (InputStream stream = blob.getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + } else if (Constants.LOB.NCLOB == classType(lobClass)) { + nclob = rs.getNClob(2); + assertEquals(nclob.length(), size); + try (InputStream stream = nclob.getAsciiStream(); + BufferedInputStream is = new BufferedInputStream(stream)) { + is.read(chunk); + assertEquals(chunk.length, size); + } + } else { + blob = rs.getBlob(2); + try (InputStream stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } } } } - + } finally { + if (null != clob) + clob.free(); + if (null != blob) + blob.free(); + if (null != nclob) + nclob.free(); + dropTables(table, stmt); } - } finally { - if (null != clob) - clob.free(); - if (null != blob) - blob.free(); - if (null != nclob) - nclob.free(); - dropTables(table); } } @@ -490,43 +473,45 @@ public void readBlobStreamAfterClosingRS() throws Exception { int size = 10000; byte[] data = new byte[size]; - random.nextBytes(data); + Constants.RANDOM.nextBytes(data); - Blob blob = null; - try (PreparedStatement ps = conn - .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { - blob = conn.createBlob(); - blob.setBytes(1, data); - ps.setInt(1, 1); - ps.setBlob(2, blob); - ps.executeUpdate(); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { + Blob blob = null; + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + blob = conn.createBlob(); + blob.setBytes(1, data); + ps.setInt(1, 1); + ps.setBlob(2, blob); + ps.executeUpdate(); - byte[] chunk = new byte[size]; - try (ResultSet rs = stmt.executeQuery( - "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0))) { - rs.next(); - - blob = rs.getBlob(2); - try (InputStream stream = blob.getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); - rs.close(); - } - try (InputStream stream = blob.getBinaryStream(); - ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + byte[] chunk = new byte[size]; + try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName() + " ORDER BY " + + table.getEscapedColumnName(0))) { + rs.next(); + + blob = rs.getBlob(2); + try (InputStream stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + rs.close(); + } + try (InputStream stream = blob.getBinaryStream(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } } + } finally { + if (null != blob) + blob.free(); + dropTables(table, stmt); } - } finally { - if (null != blob) - blob.free(); - dropTables(table); } } @@ -540,48 +525,50 @@ public void readMultipleBlobStreamsThenCloseRS() throws Exception { byte[] data = new byte[size]; Blob[] blobs = {null, null, null, null, null}; InputStream stream = null; - for (int i = 0; i < 5; i++)// create 5 blobs - { - try (PreparedStatement ps = conn - .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { - blobs[i] = conn.createBlob(); - random.nextBytes(data); - blobs[i].setBytes(1, data); - ps.setInt(1, i + 1); - ps.setBlob(2, blobs[i]); - ps.executeUpdate(); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { + for (int i = 0; i < 5; i++)// create 5 blobs + { + try (PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + blobs[i] = conn.createBlob(); + Constants.RANDOM.nextBytes(data); + blobs[i].setBytes(1, data); + ps.setInt(1, i + 1); + ps.setBlob(2, blobs[i]); + ps.executeUpdate(); + } } - } - byte[] chunk = new byte[size]; - try (ResultSet rs = stmt.executeQuery( - "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0))) { - for (int i = 0; i < 5; i++) { - rs.next(); - blobs[i] = rs.getBlob(2); - stream = blobs[i].getBinaryStream(); - try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + byte[] chunk = new byte[size]; + try (ResultSet rs = stmt.executeQuery( + "select * from " + table.getEscapedTableName() + " ORDER BY " + table.getEscapedColumnName(0))) { + for (int i = 0; i < 5; i++) { + rs.next(); + blobs[i] = rs.getBlob(2); + stream = blobs[i].getBinaryStream(); + try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } } - } - for (int i = 0; i < 5; i++) { - stream = blobs[i].getBinaryStream(); - try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { - int read = 0; - while ((read = stream.read(chunk)) > 0) - buffer.write(chunk, 0, read); - assertEquals(chunk.length, size); + for (int i = 0; i < 5; i++) { + stream = blobs[i].getBinaryStream(); + try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + int read = 0; + while ((read = stream.read(chunk)) > 0) + buffer.write(chunk, 0, read); + assertEquals(chunk.length, size); + } } + } finally { + if (null != stream) { + stream.close(); + } + dropTables(table, stmt); } - } finally { - if (null != stream) { - stream.close(); - } - dropTables(table); } } @@ -590,30 +577,30 @@ private void testUpdateLobs(String types[], Class lobClass) throws Exception int size = 10000; byte[] data = new byte[size]; - random.nextBytes(data); + Constants.RANDOM.nextBytes(data); Clob clob = null; Blob blob = null; NClob nclob = null; - try (PreparedStatement ps = conn - .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { - if (clobType == classType(lobClass)) { + try (Connection conn = getConnection(); + Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + PreparedStatement ps = conn + .prepareStatement("INSERT INTO " + table.getEscapedTableName() + " VALUES(?,?)")) { + if (Constants.LOB.CLOB == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); ps.setInt(1, 1); ps.setClob(2, clob); - } else if (nClobType == classType(lobClass)) { + } else if (Constants.LOB.NCLOB == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); nclob = conn.createNClob(); nclob.setString(1, stringData); ps.setInt(1, 1); ps.setNClob(2, nclob); - } - - else { + } else { blob = conn.createBlob(); blob.setBytes(1, data); ps.setInt(1, 1); @@ -621,16 +608,15 @@ private void testUpdateLobs(String types[], Class lobClass) throws Exception } ps.executeUpdate(); - try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { + try (ResultSet rs = stmt.executeQuery("select * from " + table.getEscapedTableName())) { while (rs.next()) { - if (clobType == classType(lobClass)) { + if (Constants.LOB.CLOB == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); clob = conn.createClob(); clob.setString(1, stringData); rs.updateClob(2, clob); - } else if (nClobType == classType(lobClass)) { + } else if (Constants.LOB.NCLOB == classType(lobClass)) { String stringData = new String(data); size = stringData.length(); nclob = conn.createNClob(); @@ -639,29 +625,28 @@ private void testUpdateLobs(String types[], Class lobClass) throws Exception } else { blob = conn.createBlob(); rs.updateBlob(2, blob); - } rs.updateRow(); } + } finally { + if (null != clob) + clob.free(); + if (null != blob) + blob.free(); + if (null != nclob) + nclob.free(); + dropTables(table, stmt); } - } finally { - if (null != clob) - clob.free(); - if (null != blob) - blob.free(); - if (null != nclob) - nclob.free(); - dropTables(table); } } - private int classType(Class type) { + private Constants.LOB classType(Class type) { if (Clob.class == type) - return clobType; + return Constants.LOB.CLOB; else if (NClob.class == type) - return nClobType; + return Constants.LOB.NCLOB; else - return blobType; + return Constants.LOB.BLOB; } private void updateLob(Object lob, Object updater, int index) throws Exception { @@ -698,15 +683,14 @@ private void updateResultSet(ResultSet rs, Object lob, int index, int length) th private Object createLob(Class lobClass) { // Randomly indicate negative length - streamLength = random.nextInt(3) < 2 ? datasize - : -1 - random.nextInt(datasize); + streamLength = Constants.RANDOM.nextInt(3) < 2 ? datasize : -1 - Constants.RANDOM.nextInt(datasize); // For streams -1 means any length, avoid to ensure that an exception is always thrown if (streamLength == -1 && (lobClass == DBCharacterStream.class || lobClass == DBBinaryStream.class)) streamLength = datasize; log.fine("Length passed into update : " + streamLength); byte[] data = new byte[datasize]; - random.nextBytes(data); + Constants.RANDOM.nextBytes(data); if (lobClass == DBCharacterStream.class) return new DBInvalidUtil().new InvalidCharacterStream(new String(data), streamLength < -1); @@ -746,7 +730,7 @@ private static DBTable createTable(DBTable table, String[] types, boolean popula return table; } - private static void dropTables(DBTable table) throws SQLException { + private static void dropTables(DBTable table, Statement stmt) throws SQLException { stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table.getEscapedTableName()) + "','U') is not null" + " drop table " + table.getEscapedTableName()); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/serial/DTOSerialTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/serial/DTOSerialTest.java index 3cf7fe82b..4bbaff397 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/serial/DTOSerialTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/serial/DTOSerialTest.java @@ -8,7 +8,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; @@ -38,7 +37,7 @@ public void testDSerial() throws Exception { sdf.setTimeZone(TimeZone.getTimeZone("Z")); dateString = sdf.format(new Date()); - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { // create a DTO @@ -53,7 +52,7 @@ public void testDSerial() throws Exception { @Test public void testESerial() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { // raise an error. @@ -105,9 +104,8 @@ private static void verifyCorrectSerialization(DateTimeOffset dto) throws Except @Test private static void verifyCorrectSend(DateTimeOffset dtn) throws Exception { // create a DTO - try (Connection conn = DriverManager.getConnection(connectionString); - SQLServerPreparedStatement ps = (SQLServerPreparedStatement) conn - .prepareStatement("SELECT CAST(? AS datetimeoffset(7)) AS" + " 'datetimeoffset IS08601' ")) { + try (Connection conn = getConnection(); SQLServerPreparedStatement ps = (SQLServerPreparedStatement) conn + .prepareStatement("SELECT CAST(? AS datetimeoffset(7)) AS" + " 'datetimeoffset IS08601' ")) { ps.setDateTimeOffset(1, dtn); try (ResultSet rs = ps.executeQuery()) { rs.next(); 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 9bcce59de..ae577a255 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 @@ -8,13 +8,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.lang.reflect.Field; import java.sql.BatchUpdateException; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; @@ -44,7 +42,7 @@ public class BatchExecuteWithErrorsTest extends AbstractTest { public static final Logger log = Logger.getLogger("BatchExecuteWithErrors"); - Connection con = null; + final String tableName = RandomUtil.getIdentifier("t_Repro47239"); final String insertStmt = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (999, 'HELLO', '4/12/1994')"; @@ -53,6 +51,10 @@ public class BatchExecuteWithErrorsTest extends AbstractTest { final String dateConversionError = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (999999, 'Hello again', 'asdfasdf')"; + String warning; + String error; + String severe; + /** * Batch test * @@ -88,18 +90,7 @@ public void Repro47239largeUseBulkCopyAPI() throws Exception { } private void Repro47239Internal(String mode) throws Exception { - 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 " + AbstractSQLGenerator.escapeIdentifier(tableName) - + " values (999999, 'Hello again', 'asdfasdf')"; - - String warning; - String error; - String severe; - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { if (isSqlAzure()) { // SQL Azure will throw exception for "raiserror WITH LOG", so the following RAISERROR statements have // not @@ -129,13 +120,7 @@ private void Repro47239Internal(String mode) throws Exception { int[] expectedUpdateCounts; String actualExceptionText; - // SQL Server 2005 driver - try { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - } catch (ClassNotFoundException e1) { - fail(e1.toString()); - } - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI((SQLServerConnection) conn); } @@ -306,22 +291,17 @@ private void Repro47239Internal(String mode) throws Exception { } } } finally { - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } } private void Repro47239largeInternal(String mode) throws Exception { - assumeTrue("JDBC42".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); // the DBConnection for detecting whether the server is SQL Azure or SQL Server. - try (Connection con = DriverManager.getConnection(connectionString)) { - final String warning; - final String error; - final String severe; + try (Connection con = getConnection()) { if (isSqlAzure()) { // SQL Azure will throw exception for "raiserror WITH LOG", so the following RAISERROR statements have // not @@ -351,10 +331,7 @@ private void Repro47239largeInternal(String mode) throws Exception { long[] expectedUpdateCounts; String actualExceptionText; - // SQL Server 2005 driver - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - - try (Connection conn = DriverManager.getConnection(connectionString)) { + try (Connection conn = getConnection()) { if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI((SQLServerConnection) conn); } 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 42b5ef89b..d3de5182e 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 @@ -10,7 +10,6 @@ import java.lang.reflect.Field; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -31,6 +30,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.PrepUtil; /** @@ -85,8 +85,7 @@ private void testExecuteBatch1Internal(String mode) { int i = 0; int retValue[] = {0, 0, 0}; int updateCountlen = 0; - try (Connection connection = DriverManager - .getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { String sPrepStmt = "update " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + " set PRICE=PRICE*20 where TYPE_ID=?"; @@ -137,8 +136,7 @@ private void testExecuteBatch1Internal(String mode) { } private static void createTable() throws SQLException { - try (Connection connection = DriverManager - .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + " (TYPE_ID int, TYPE_DESC varchar(32), primary key(TYPE_ID)) "; @@ -171,8 +169,7 @@ private static void createTable() throws SQLException { private void testAddBatch1Internal(String mode) { int i = 0; int retValue[] = {0, 0, 0}; - try (Connection connection = DriverManager - .getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { + try (Connection connection = PrepUtil.getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { String sPrepStmt = "update " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + " set PRICE=PRICE*20 where TYPE_ID=?"; @@ -245,8 +242,7 @@ public static void testSetup() throws TestAbortedException, Exception { } private static void dropTable() throws SQLException { - try (Connection connection = DriverManager - .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); + try (Connection connection = PrepUtil.getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { 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 897c9ade3..62e300227 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 @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; @@ -26,6 +25,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -46,8 +46,7 @@ public class BatchTriggerTest extends AbstractTest { */ @Test public void statementTest() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.addBatch(insertQuery); stmt.executeBatch(); fail(TestResource.getResource("R_expectedExceptionNotThrown")); @@ -63,7 +62,7 @@ public void statementTest() throws SQLException { */ @Test public void preparedStatementTest() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); + try (Connection connection = getConnection(); PreparedStatement pstmt = connection.prepareStatement(insertQuery)) { pstmt.addBatch(); @@ -82,8 +81,7 @@ public void preparedStatementTest() throws SQLException { * @throws SQLException */ private static void createTrigger(String triggerName) throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { String sql = "create trigger " + triggerName + " on " + AbstractSQLGenerator.escapeIdentifier(tableName) + " for insert " + "as " + "begin " + "if (select col1 from " + AbstractSQLGenerator.escapeIdentifier(tableName) + ") > 10 " + "begin " + "return " + "end " @@ -99,8 +97,7 @@ private static void createTrigger(String triggerName) throws SQLException { * @throws SQLException */ private static void createTable() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " ( col1 int, col2 varchar(50), col3 varchar(10), col4 int)"; stmt.execute(sql); @@ -120,29 +117,15 @@ public static void testSetup() throws TestAbortedException, Exception { 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); + try (Connection connection = getConnection(); SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { - stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" - + " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n" - + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + ";"); - dropTable(); + TestUtils.dropTriggerIfExists(triggerName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); createTable(); createTrigger(AbstractSQLGenerator.escapeIdentifier(triggerName)); } } - /** - * Drop the table - * - * @throws SQLException - */ - private static void dropTable() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { - TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); - } - } - /** * Cleaning up * @@ -150,13 +133,13 @@ private static void dropTable() throws SQLException { */ @AfterAll public static void terminateVariation() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); + try (Connection connection = getConnection(); SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { - - dropTable(); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" + " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n" - + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + ";"); + + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + + Constants.SEMI_COLON); } } } 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 ee98c17dc..8d8586ddb 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 @@ -8,7 +8,6 @@ import java.sql.CallableStatement; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -42,8 +41,7 @@ public class CallableMixedTest extends AbstractTest { @Test @DisplayName("Test CallableMix") public void datatypesTest() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement();) { + try (Connection connection = getConnection(); Statement statement = connection.createStatement();) { statement.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1_int int primary key, col2 int)"); 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 1e3863fd5..ceff67cbc 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 @@ -13,7 +13,6 @@ import java.lang.reflect.Method; import java.sql.CallableStatement; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; @@ -42,7 +41,6 @@ public class LimitEscapeTest extends AbstractTest { public static final Logger log = Logger.getLogger("LimitEscape"); 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("\'", ""); @@ -275,536 +273,561 @@ public static void createAndPopulateTables(Connection conn) throws Exception { @DisplayName("initAndVerifyQueries") public void initAndVerifyQueries() throws Exception { Query qry; - // 1 - // Test whether queries without limit syntax works - 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 - new String[][] {{"col3", "col4"}}); // string column values - qry.execute(conn); - - // 2 - // Test parentheses in limit syntax - 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 - new String[][] {{"col3", "col4"}, {"row2 ' with ' quote", "row2 with limit {limit 22} {limit ?}"}}); // string - // column - // values - qry.execute(conn); - - // 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 " + 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 - new int[][] {{3, 3}}, // int column values - null); // string column values - qry.execute(conn); - - // 4 - // Test quotes/limit syntax/scalar function in string literal. Also test real limit syntax in query. - 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 - new int[][] {{4, 4}}, // int column values - null); // string column values - qry.execute(conn); - - // 5 - // Test openquery/openrowset in string literals - 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 - new int[][] {{5}}, // int column values - null); // string column values - qry.execute(conn); - - // 6 - // Test limit syntax in subquery as well as in outer query - 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 - null); // string column values - qry.execute(conn); - - // 7 - // Test multiple parentheses in limit syntax and in subquery - 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 - null); // string column values - qry.execute(conn); - - // 8 - // Test limit syntax in multiple subqueries, also test arbitrary spaces in limit syntax - qry = new Query( - "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 - null, // int column values - null); // string column values - qry.execute(conn); - - // 9 - // Test limit syntax in multiple levels of nested subqueries - qry = new Query( - "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 - null, // int column values - null); // string column values - qry.execute(conn); - - // 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 " + 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 - null, // int column values - null); // string column values - qry.execute(conn); - - // 11 - // Test multiple parentheses/spaces in limit syntax, also test '[]' in columns - 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 - new String[][] {{"col3", "col4"}, {"row2 ' with ' quote", "row2 with limit {limit 22} {limit ?}"}}); // string - // column - // values - qry.execute(conn); - - // 12 - // Test complicated query with nested subquery having limit syntax - qry = new Query( - "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 - null, // int column values - null); // string column values - qry.execute(conn); - - // 13 - // Test prepared statements with limit syntax with multiple parentheses/spaces - 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 - new String[][] {{"col3", "col4"}}, 1); - qry.execute(conn); - - // 14 - // Test prepared statements with limit syntax - 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 - new String[][] {{"col3", "col4"}}, 1); - qry.execute(conn); - - // 15 - // Test prepared statements with limit syntax with multiple parentheses/spaces - 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 - new String[][] {{"col3", "col4"}}, 1); - qry.execute(conn); - - // 16 - // Test prepared statements with limit syntax with subqueries - 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 - new String[][] {{"col3", "col4"}}, 2); - qry.execute(conn); - - // 17 - // Test callable statements as they are also translated by the driver - 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 - new String[][] {{"col3", "col4"}}, 0); - qry.execute(conn); - - // 18 - // Test callable statements with limit syntax in string literals - qry = new CallableQuery( - "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 - 5, // # of columns - new int[] {2}, // id column values - new int[][] {{2, 2}}, // int column values - new String[][] {{"row2 ' with ' quote", "row2 with limit {limit 22} {limit ?}"}}, 0); - qry.execute(conn); - - // 19 - // Test callable statements with subquery/limit syntax in string literals - 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 - new int[][] {{3, 3}}, // int column values - new String[][] {{"row3 with subquery (select * from t1)", - "row3 with subquery (select * from (select * from t1) {limit 4})"}}, - 0); - qry.execute(conn); - - // 20 - // Test callable statements with quotes/scalar functions/limit syntax in string literals - 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 - new int[][] {{4, 4}}, // int column value - new String[][] {{"select * from t1 {limit 4} 'quotes' (braces)", "ucase(scalar function)"}}, 0); - qry.execute(conn); - - // 21 - // Test callable statement escape syntax with quotes/scalar functions/limit syntax in string literals - qry = new CallableQuery( - "{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 - new String[][] {{"select * from t1 {limit 4} 'quotes' (braces)", "ucase(scalar function)"}}, 0); - qry.execute(conn); - - // 22 - // Test callable statement escape syntax with openrowquery/openrowset/quotes in string literals - 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 - 5, // # of columns - new int[] {5}, // id column values - new int[][] {{5, 5}}, // int column value - new String[][] {{"openquery('server', 'query')", "openrowset('server','connection string','query')"}}, - 0); - qry.execute(conn); - - // Do not execute this query as no lnked_server is setup. Only verify the translation for it. - // 23 - // Test openquery syntax translation with limit syntax - qry = new Query( - "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 - new String[][] {{"openquery('server', 'query')", "openrowset('server','connection string','query')"}}); - - // Do not execute this query as no lnked_server is setup. Only verify the translation for it. - // 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 " - + 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 - new int[][] {{5, 5}}, // int column value - new String[][] {{"openquery('server', 'query')", "openrowset('server','connection string','query')"}}); - - // 25 - // Test offset syntax in string literals - 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 - null); - qry.execute(conn); - - // 26 - // Do not execute this query as it is a batch query, needs to be handled differently. - // Only test the syntax translation. - // Test batch query. - qry = new Query( - "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 - null); - - // 27 - // Execute query, and verify exception for unclosed quotation marks. - 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Unclosed quotation mark after the character string 'abcd'."); - qry.execute(conn); - - // 28 - // Execute query, and verify exception for unclosed subquery. - 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 '" + table1 + "'."); - qry.execute(conn); - - // 29 - // Execute query, and verify exception for syntax error in select. - 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '*'."); - qry.execute(conn); - - // 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 " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", - "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", 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 '{'."); - qry.execute(conn); - - // 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 " + 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '{'."); - qry.execute(conn); - - // 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 " + 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '{'."); - qry.execute(conn); - - // 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 " + 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '{'."); - qry.execute(conn); - - // 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 " + 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '{'."); - qry.execute(conn); - - // 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 " + AbstractSQLGenerator.escapeIdentifier(table1) + "(col3) values({limit 1})", - "insert into " + AbstractSQLGenerator.escapeIdentifier(table1) + "(col3) values({limit 1})", 0, // # of + try (Connection conn = getConnection()) { + // 1 + // Test whether queries without limit syntax works + 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 + new String[][] {{"col3", "col4"}}); // string column values + qry.execute(conn); + + // 2 + // Test parentheses in limit syntax + 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 + new String[][] {{"col3", "col4"}, + {"row2 ' with ' quote", "row2 with limit {limit 22} {limit ?}"}}); // string + // column + // values + qry.execute(conn); + + // 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 " + 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 + new int[][] {{3, 3}}, // int column values + null); // string column values + qry.execute(conn); + + // 4 + // Test quotes/limit syntax/scalar function in string literal. Also test real limit syntax in query. + 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 + new int[][] {{4, 4}}, // int column values + null); // string column values + qry.execute(conn); + + // 5 + // Test openquery/openrowset in string literals + 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 + new int[][] {{5}}, // int column values + null); // string column values + qry.execute(conn); + + // 6 + // Test limit syntax in subquery as well as in outer query + 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 + null); // string column values + qry.execute(conn); + + // 7 + // Test multiple parentheses in limit syntax and in subquery + 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 + null); // string column values + qry.execute(conn); + + // 8 + // Test limit syntax in multiple subqueries, also test arbitrary spaces in limit syntax + qry = new Query( + "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 + null, // int column values + null); // string column values + qry.execute(conn); + + // 9 + // Test limit syntax in multiple levels of nested subqueries + qry = new Query( + "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 + null, // int column values + null); // string column values + qry.execute(conn); + + // 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 " + 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 + null, // int column values + null); // string column values + qry.execute(conn); + + // 11 + // Test multiple parentheses/spaces in limit syntax, also test '[]' in columns + 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 + new String[][] {{"col3", "col4"}, + {"row2 ' with ' quote", "row2 with limit {limit 22} {limit ?}"}}); // string + // column + // values + qry.execute(conn); + + // 12 + // Test complicated query with nested subquery having limit syntax + qry = new Query( + "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 + null, // int column values + null); // string column values + qry.execute(conn); + + // 13 + // Test prepared statements with limit syntax with multiple parentheses/spaces + 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 + new String[][] {{"col3", "col4"}}, 1); + qry.execute(conn); + + // 14 + // Test prepared statements with limit syntax + 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 + new String[][] {{"col3", "col4"}}, 1); + qry.execute(conn); + + // 15 + // Test prepared statements with limit syntax with multiple parentheses/spaces + 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 + new String[][] {{"col3", "col4"}}, 1); + qry.execute(conn); + + // 16 + // Test prepared statements with limit syntax with subqueries + 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 + new String[][] {{"col3", "col4"}}, 2); + qry.execute(conn); + + // 17 + // Test callable statements as they are also translated by the driver + 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 + new String[][] {{"col3", "col4"}}, 0); + qry.execute(conn); + + // 18 + // Test callable statements with limit syntax in string literals + qry = new CallableQuery("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 + 5, // # of columns + new int[] {2}, // id column values + new int[][] {{2, 2}}, // int column values + new String[][] {{"row2 ' with ' quote", "row2 with limit {limit 22} {limit ?}"}}, 0); + qry.execute(conn); + + // 19 + // Test callable statements with subquery/limit syntax in string literals + 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 + new int[][] {{3, 3}}, // int column values + new String[][] {{"row3 with subquery (select * from t1)", + "row3 with subquery (select * from (select * from t1) {limit 4})"}}, + 0); + qry.execute(conn); + + // 20 + // Test callable statements with quotes/scalar functions/limit syntax in string literals + 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 + new int[][] {{4, 4}}, // int column value + new String[][] {{"select * from t1 {limit 4} 'quotes' (braces)", "ucase(scalar function)"}}, 0); + qry.execute(conn); + + // 21 + // Test callable statement escape syntax with quotes/scalar functions/limit syntax in string literals + qry = new CallableQuery( + "{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 + new String[][] {{"select * from t1 {limit 4} 'quotes' (braces)", "ucase(scalar function)"}}, 0); + qry.execute(conn); + + // 22 + // Test callable statement escape syntax with openrowquery/openrowset/quotes in string literals + 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 + 5, // # of columns + new int[] {5}, // id column values + new int[][] {{5, 5}}, // int column value + new String[][] { + {"openquery('server', 'query')", "openrowset('server','connection string','query')"}}, + 0); + qry.execute(conn); + + // Do not execute this query as no lnked_server is setup. Only verify the translation for it. + // 23 + // Test openquery syntax translation with limit syntax + qry = new Query( + "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 + new String[][] { + {"openquery('server', 'query')", "openrowset('server','connection string','query')"}}); + + // Do not execute this query as no lnked_server is setup. Only verify the translation for it. + // 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 " + + 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 + new int[][] {{5, 5}}, // int column value + new String[][] { + {"openquery('server', 'query')", "openrowset('server','connection string','query')"}}); + + // 25 + // Test offset syntax in string literals + 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 + null); + qry.execute(conn); + + // 26 + // Do not execute this query as it is a batch query, needs to be handled differently. + // Only test the syntax translation. + // Test batch query. + qry = new Query( + "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 + null); + + // 27 + // Execute query, and verify exception for unclosed quotation marks. + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Unclosed quotation mark after the character string 'abcd'."); + qry.execute(conn); + + // 28 + // Execute query, and verify exception for unclosed subquery. + 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 '" + table1 + "'."); + qry.execute(conn); + + // 29 + // Execute query, and verify exception for syntax error in select. + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Incorrect syntax near '*'."); + qry.execute(conn); + + // 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 " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", 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 '{'."); + qry.execute(conn); + + // 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 " + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Incorrect syntax near '{'."); + qry.execute(conn); + + // 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 " + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Incorrect syntax near '{'."); + qry.execute(conn); + + // 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 " + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Incorrect syntax near '{'."); + qry.execute(conn); + + // 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 " + 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '1'."); - qry.execute(conn); - - // 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 " + 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '{'."); - qry.execute(conn); - - // 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 " + 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 - null); // string column values - // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near '{'."); - qry.execute(conn); - - log.fine("Tranlsation verified for " + Query.queryCount + " queries"); + 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 '{'."); + qry.execute(conn); + + // 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 " + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Incorrect syntax near '1'."); + qry.execute(conn); + + // 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 " + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Incorrect syntax near '{'."); + qry.execute(conn); + + // 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 " + 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 + null); // string column values + // Verified that SQL Server throws an exception with this message for similar errors. + qry.setExceptionMsg("Incorrect syntax near '{'."); + qry.execute(conn); + + log.fine("Tranlsation verified for " + Query.queryCount + " queries"); + } } /** @@ -851,8 +874,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. - new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit (2))}", - "", 0, // # of rows + new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit (2))}", "", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -869,11 +892,10 @@ public void verifyOffsetException() throws Exception { */ @BeforeAll public static void beforeAll() { - try { - conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection()) { createAndPopulateTables(conn); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -884,8 +906,7 @@ public static void beforeAll() { */ @AfterAll public static void afterAll() throws Exception { - - try (Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table3), stmt); @@ -893,10 +914,6 @@ public static void afterAll() throws Exception { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (Exception ex) { fail(ex.toString()); - } finally { - conn.close(); } - } - } 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 2d00d9cdc..c55e09462 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 @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; @@ -23,6 +22,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; @@ -36,15 +36,15 @@ public class MergeTest extends AbstractTest { 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) + + "', N'U') IS NOT NULL DROP TABLE " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + + Constants.SEMI_COLON + " 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 " + 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) + Constants.SEMI_COLON + " CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + " ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) @@ -92,7 +92,7 @@ public void runTest() throws Exception { @AfterAll public static void afterAll() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(cricketTeams), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated), stmt); 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 c5a654cf2..c4127b2b5 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 @@ -8,7 +8,6 @@ import java.sql.CallableStatement; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; @@ -44,8 +43,7 @@ public class NamedParamMultiPartTest extends AbstractTest { public static void beforeAll() throws SQLException { procedureName = RandomUtil.getIdentifier("mystoredproc"); - try (Connection connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement()) { + try (Connection connection = getConnection(); Statement statement = connection.createStatement()) { 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) + "'"); @@ -59,7 +57,7 @@ public static void beforeAll() throws SQLException { */ @Test public void update1() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + try (Connection connection = getConnection(); CallableStatement cs = connection .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); @@ -75,7 +73,7 @@ public void update1() throws Exception { */ @Test public void update2() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + try (Connection connection = getConnection(); CallableStatement cs = connection .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); @@ -93,7 +91,7 @@ public void update2() throws Exception { public void update3() throws Exception { String catalog = connection.getCatalog(); String storedproc = "[" + catalog + "]" + ".[dbo]." + AbstractSQLGenerator.escapeIdentifier(procedureName); - try (Connection connection = DriverManager.getConnection(connectionString); + try (Connection connection = getConnection(); CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); @@ -109,7 +107,7 @@ public void update3() throws Exception { */ @Test public void update4() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + try (Connection connection = getConnection(); CallableStatement cs = connection .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); @@ -125,7 +123,7 @@ public void update4() throws Exception { */ @Test public void update5() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + try (Connection connection = getConnection(); CallableStatement cs = connection .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); @@ -142,7 +140,7 @@ public void update5() throws Exception { public void update6() throws Exception { String catalog = connection.getCatalog(); String storedproc = catalog + ".dbo." + AbstractSQLGenerator.escapeIdentifier(procedureName); - try (Connection connection = DriverManager.getConnection(connectionString); + try (Connection connection = getConnection(); CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); @@ -158,8 +156,7 @@ public void update6() throws Exception { */ @AfterAll public static void afterAll() throws SQLException { - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { 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 86e150397..0bb0b2785 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 @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -29,6 +28,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; /** @@ -64,7 +64,7 @@ public class PQImpsTest extends AbstractTest { */ @BeforeAll public static void BeforeTests() throws SQLException { - connection = (SQLServerConnection) DriverManager.getConnection(connectionString); + connection = (SQLServerConnection) getConnection(); stmt = connection.createStatement(); version = getSQLServerVersion(); createMultipleTypesTable(); @@ -101,7 +101,7 @@ public void numericTest() throws SQLException { deleteNumeric(); checkNumericMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -127,7 +127,7 @@ public void charTests() throws SQLException { deleteChar(); checkCharMetaData(4); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -155,7 +155,7 @@ public void binaryTests() throws SQLException { deleteBinary(); checkBinaryMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -183,7 +183,7 @@ public void temporalTests() throws SQLException { deleteDateAndTime(); checkDateAndTimeMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -203,7 +203,7 @@ public void MultipleTypesTableTest() throws Exception { testMixedWithHardcodedValues(); } } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -291,13 +291,13 @@ private static void compareParameterMetaData(ParameterMetaData pmd, int index, S "Parameter class Name error:\n" + "expected: " + expectedClassName + "\n" + "actual: " + pmd.getParameterClassName(index)); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } try { assertTrue(pmd.getParameterType(index) == expectedType, "getParameterType: " + TestResource.getResource("R_valueNotMatch") + expectedType + ", " + pmd.getParameterType(index)); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } try { @@ -305,20 +305,20 @@ private static void compareParameterMetaData(ParameterMetaData pmd, int index, S "getParameterTypeName: " + TestResource.getResource("R_valueNotMatch") + expectedTypeName + ", " + pmd.getParameterTypeName(index)); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } try { assertTrue(pmd.getPrecision(index) == expectedPrecision, "getPrecision: " + TestResource.getResource("R_valueNotMatch") + expectedPrecision + ", " + pmd.getPrecision(index)); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } try { assertTrue(pmd.getScale(index) == expectedScale, "getScale: " + TestResource.getResource("R_valueNotMatch") + expectedScale + ", " + pmd.getScale(index)); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -381,7 +381,7 @@ private static void updateNumeric() throws SQLException { String sql = "update " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " set " + "c1 = ?," + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?," + "c10 = ?," - + "c11 = ?," + "c12 = ?," + "c13 = ?," + "c14 = ?," + "c15 = ?" + ";"; + + "c11 = ?," + "c12 = ?," + "c13 = ?," + "c14 = ?," + "c15 = ?" + Constants.SEMI_COLON; pstmt = connection.prepareStatement(sql); @@ -397,7 +397,7 @@ private static void deleteNumeric() throws SQLException { 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 = ?" + ";"; + + "c14 = ? and " + "c15 = ?" + Constants.SEMI_COLON; pstmt = connection.prepareStatement(sql); @@ -472,7 +472,7 @@ private static void insertChar() throws SQLException { private static void updateChar() throws SQLException { String sql = "update " + AbstractSQLGenerator.escapeIdentifier(charTable) + " set " + "c1 = ?," + "c2 = ?," - + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?" + ";"; + + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?" + Constants.SEMI_COLON; pstmt = connection.prepareStatement(sql); @@ -540,7 +540,7 @@ private static void insertBinary() throws SQLException { private static void updateBinary() throws SQLException { String sql = "update " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " set " + "c1 = ?," + "c2 = ?" - + ";"; + + Constants.SEMI_COLON; pstmt = connection.prepareStatement(sql); @@ -555,7 +555,7 @@ private static void updateBinary() throws SQLException { private static void deleteBinary() throws SQLException { String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " where " + "c1 = ? and " - + "c2 = ?" + ";"; + + "c2 = ?" + Constants.SEMI_COLON; pstmt = connection.prepareStatement(sql); @@ -598,7 +598,8 @@ private static void insertDateAndTime() throws SQLException { private static void updateDateAndTime() throws SQLException { String sql = "update " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " set " + "c1 = ?," - + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?" + ";"; + + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?" + + Constants.SEMI_COLON; pstmt = connection.prepareStatement(sql); @@ -613,7 +614,7 @@ private static void deleteDateAndTime() throws SQLException { 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 = ?" + ";"; + + "c7 = ? and " + "c8 = ? and " + "c9 = ?" + Constants.SEMI_COLON; pstmt = connection.prepareStatement(sql); @@ -656,7 +657,7 @@ private static void createTablesForCompexQueries() throws SQLException { try { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } sql = "create table " + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + " (" @@ -665,7 +666,7 @@ private static void createTablesForCompexQueries() throws SQLException { try { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } sql = "create table " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable) + " (" @@ -676,7 +677,7 @@ private static void createTablesForCompexQueries() throws SQLException { try { stmt.execute(sql); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -770,7 +771,7 @@ public void testSubquery() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 3, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.Long", -5, "BIGINT", 19, 0); @@ -808,7 +809,7 @@ public void testJoin() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 2, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.Integer", 4, "int", 10, 0); @@ -841,7 +842,7 @@ public void testMerge() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 2, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.String", 1, "CHAR", 30, 0); @@ -895,7 +896,7 @@ private static void testInsertMultipleTypes() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 30, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.math.BigDecimal", 3, "decimal", 18, 0); @@ -951,7 +952,7 @@ public void testNoParameter() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 0, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -985,7 +986,7 @@ private static void testMixedWithHardcodedValues() throws SQLException { assertEquals(pmd.getParameterCount(), 21, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.math.BigDecimal", 3, "decimal", 10, 5); @@ -1033,7 +1034,7 @@ public void testOrderBy() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 4, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.String", 12, "varchar", 50, 0); @@ -1062,7 +1063,7 @@ private void testGroupBy() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 4, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.String", 12, "varchar", 50, 0); @@ -1091,7 +1092,7 @@ public void testLower() throws SQLException { assertEquals(pmd.getParameterCount(), 4, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.String", 12, "varchar", 50, 0); @@ -1119,7 +1120,7 @@ public void testPower() throws SQLException { pmd = pstmt.getParameterMetaData(); assertEquals(pmd.getParameterCount(), 4, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.String", 12, "varchar", 50, 0); @@ -1159,7 +1160,7 @@ public void testAllInOneQuery() throws SQLException { assertEquals(pmd.getParameterCount(), 3, TestResource.getResource("R_paramNotRecognized")); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } compareParameterMetaData(pmd, 1, "java.lang.Short", 5, "smallint", 5, 0); @@ -1183,7 +1184,7 @@ public void testQueryWithMultipleLineComments1() throws SQLException { pstmt.getParameterMetaData(); pstmt.executeQuery(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1203,7 +1204,7 @@ public void testQueryWithMultipleLineComments2() throws SQLException { pstmt.getParameterMetaData(); pstmt.executeQuery(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1220,7 +1221,7 @@ public void testQueryWithMultipleLineCommentsInsert() throws SQLException { try { pstmt.getParameterMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1237,7 +1238,7 @@ public void testQueryWithMultipleLineCommentsUpdate() throws SQLException { try { pstmt.getParameterMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1254,7 +1255,7 @@ public void testQueryWithMultipleLineCommentsDeletion() throws SQLException { try { pstmt.getParameterMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1273,7 +1274,7 @@ public void testQueryWithSingleLineComments1() throws SQLException { pstmt.getParameterMetaData(); pstmt.executeQuery(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1292,7 +1293,7 @@ public void testQueryWithSingleLineComments2() throws SQLException { pstmt.getParameterMetaData(); pstmt.executeQuery(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1311,7 +1312,7 @@ public void testQueryWithSingleLineComments3() throws SQLException { pstmt.getParameterMetaData(); pstmt.executeQuery(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1328,7 +1329,7 @@ public void testQueryWithSingleLineCommentsInsert() throws SQLException { try { pstmt.getParameterMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1345,7 +1346,7 @@ public void testQueryWithSingleLineCommentsUpdate() throws SQLException { try { pstmt.getParameterMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1362,7 +1363,7 @@ public void testQueryWithSingleLineCommentsDeletion() throws SQLException { try { pstmt.getParameterMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1379,7 +1380,7 @@ public void testQueryWithSpaceAndEndCommentMarkInColumnName() throws SQLExceptio try { pstmt.getParameterMetaData(); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } @@ -1400,7 +1401,7 @@ public void testComplexQueryWithMultipleTables() throws SQLException { assertTrue(2 == parameterCount, "Parameter Count should be 2."); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java index ba8a683cc..bdea0a210 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java @@ -9,7 +9,6 @@ import java.sql.CallableStatement; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; @@ -46,8 +45,7 @@ public class PoolableTest extends AbstractTest { @Test @DisplayName("Poolable Test") public void poolableTest() throws SQLException, ClassNotFoundException { - try (Connection conn = DriverManager.getConnection(connectionString); - Statement statement = conn.createStatement()) { + try (Connection conn = getConnection(); Statement statement = conn.createStatement()) { // First get the default values boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); assertEquals(isPoolable, false, "SQLServerStatement: " + TestResource.getResource("R_incorrectDefault")); @@ -89,7 +87,7 @@ public void poolableTest() throws SQLException, ClassNotFoundException { */ @AfterAll public static void afterAll() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { TestUtils.dropProcedureIfExists("ProcName", stmt); } catch (Exception ex) { fail(ex.toString()); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java index f1cfa0bb0..8220dad3c 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 @@ -12,7 +12,6 @@ import java.lang.reflect.Field; import java.sql.BatchUpdateException; -import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -34,6 +33,8 @@ import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Constants; +import com.microsoft.sqlserver.testframework.PrepUtil; @RunWith(JUnitPlatform.class) @@ -69,7 +70,7 @@ private int executeSQLReturnFirstInt(SQLServerConnection conn, String sql) throw public void testBatchedUnprepare() throws SQLException { SQLServerConnection conOuter = null; - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) getConnection()) { conOuter = con; // Turn off use of prepared statement cache. @@ -171,7 +172,7 @@ public void testStatementPoolingUseBulkCopyAPI() throws Exception { public void testStatementPoolingEviction() throws SQLException { for (int testNo = 0; testNo < 2; ++testNo) { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) getConnection()) { int cacheSize = 10; int discardedStatementCount = testNo == 0 ? 5 /* batched unprepares */ : 0 /* regular unprepares */; @@ -267,7 +268,7 @@ public void testPrepareRace() throws Exception { CountDownLatch latch = new CountDownLatch(3); AtomicReference exception = new AtomicReference<>(); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) getConnection()) { for (int i = 0; i < 3; i++) { execServiceThread.submit(() -> { for (int j = 0; j < 500; j++) { @@ -326,7 +327,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws // Test disableStatementPooling=true String connectionStringDisableStatementPooling = connectionString + ";disableStatementPooling=true;"; - try (SQLServerConnection connectionDisableStatementPooling = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionDisableStatementPooling = (SQLServerConnection) PrepUtil .getConnection(connectionStringDisableStatementPooling)) { // to turn on caching and check if disableStatementPooling is true, even setting cachesize won't matter and // will disable it. @@ -337,7 +338,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws // Test disableStatementPooling=false String connectionStringEnableStatementPooling = connectionString + ";disableStatementPooling=false;"; - try (SQLServerConnection connectionEnableStatementPooling = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionEnableStatementPooling = (SQLServerConnection) PrepUtil .getConnection(connectionStringEnableStatementPooling)) { connectionEnableStatementPooling.setStatementPoolingCacheSize(10); // to turn on caching. @@ -352,7 +353,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws String connectionPropertyStringEnableStatementPooling = connectionString + ";disableStatementPooling=false;statementPoolingCacheSize=10"; - try (SQLServerConnection connectionPropertyEnableStatementPooling = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionPropertyEnableStatementPooling = (SQLServerConnection) PrepUtil .getConnection(connectionPropertyStringEnableStatementPooling)) { // for now, it won't affect if disable is false or true. Since statementPoolingCacheSize is set to 0 as // default. @@ -365,7 +366,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws String connectionPropertyStringDisableStatementPooling = connectionString + ";disableStatementPooling=true;statementPoolingCacheSize=10"; - try (SQLServerConnection connectionPropertyDisableStatementPooling = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionPropertyDisableStatementPooling = (SQLServerConnection) PrepUtil .getConnection(connectionPropertyStringDisableStatementPooling)) { assertTrue(0 < connectionPropertyDisableStatementPooling.getStatementPoolingCacheSize()); // for now, it // won't @@ -385,7 +386,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws String connectionPropertyStringDisableStatementPooling2 = connectionString + ";disableStatementPooling=false;statementPoolingCacheSize=0"; - try (SQLServerConnection connectionPropertyDisableStatementPooling2 = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionPropertyDisableStatementPooling2 = (SQLServerConnection) PrepUtil .getConnection(connectionPropertyStringDisableStatementPooling2)) { assertTrue(0 == connectionPropertyDisableStatementPooling2.getStatementPoolingCacheSize()); // for now, it // won't @@ -406,14 +407,14 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws // Test EnablePrepareOnFirstPreparedStatementCall String connectionStringNoExecuteSQL = connectionString + ";enablePrepareOnFirstPreparedStatementCall=true;"; - try (SQLServerConnection connectionNoExecuteSQL = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionNoExecuteSQL = (SQLServerConnection) PrepUtil .getConnection(connectionStringNoExecuteSQL)) { assertSame(true, connectionNoExecuteSQL.getEnablePrepareOnFirstPreparedStatementCall()); } // Test ServerPreparedStatementDiscardThreshold String connectionStringThreshold3 = connectionString + ";ServerPreparedStatementDiscardThreshold=3;"; - try (SQLServerConnection connectionThreshold3 = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionThreshold3 = (SQLServerConnection) PrepUtil .getConnection(connectionStringThreshold3)) { assertSame(3, connectionThreshold3.getServerPreparedStatementDiscardThreshold()); } @@ -421,7 +422,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws // Test combination of EnablePrepareOnFirstPreparedStatementCall and ServerPreparedStatementDiscardThreshold String connectionStringThresholdAndNoExecuteSQL = connectionString + ";ServerPreparedStatementDiscardThreshold=3;enablePrepareOnFirstPreparedStatementCall=true;"; - try (SQLServerConnection connectionThresholdAndNoExecuteSQL = (SQLServerConnection) DriverManager + try (SQLServerConnection connectionThresholdAndNoExecuteSQL = (SQLServerConnection) PrepUtil .getConnection(connectionStringThresholdAndNoExecuteSQL)) { assertSame(true, connectionThresholdAndNoExecuteSQL.getEnablePrepareOnFirstPreparedStatementCall()); assertSame(3, connectionThresholdAndNoExecuteSQL.getServerPreparedStatementDiscardThreshold()); @@ -431,8 +432,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws // Test that an error is thrown for invalid connection string property values (non int/bool). String connectionStringThresholdError = connectionString + ";ServerPreparedStatementDiscardThreshold=" + invalidValue; - try (SQLServerConnection con = (SQLServerConnection) DriverManager - .getConnection(connectionStringThresholdError)) { + try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(connectionStringThresholdError)) { fail("Error for invalid ServerPreparedStatementDiscardThresholdexpected."); } catch (SQLException e) { assert (e.getMessage().equalsIgnoreCase(String.format( @@ -441,7 +441,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws String connectionStringNoExecuteSQLError = connectionString + ";enablePrepareOnFirstPreparedStatementCall=" + invalidValue; - try (SQLServerConnection con = (SQLServerConnection) DriverManager + try (SQLServerConnection con = (SQLServerConnection) PrepUtil .getConnection(connectionStringNoExecuteSQLError)) { fail("Error for invalid enablePrepareOnFirstPreparedStatementCall expected."); } catch (SQLException e) { @@ -450,7 +450,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws } // Verify instance setting is followed. - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) getConnection()) { // Turn off use of prepared statement cache. con.setStatementPoolingCacheSize(0); @@ -488,7 +488,7 @@ public void testStatementPoolingPreparedStatementExecAndUnprepareConfig() throws private void testStatementPoolingInternal(String mode) throws Exception { // Test % handle re-use - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) getConnection()) { if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI(con); } @@ -523,7 +523,7 @@ private void testStatementPoolingInternal(String mode) throws Exception { } } - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) getConnection()) { if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI(con); } @@ -635,7 +635,8 @@ private void testStatementPoolingInternal(String mode) throws Exception { // Execute new statement with different SQL text and verify it does NOT get same handle (should now fall // back to using sp_executesql). SQLServerPreparedStatement outer = null; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(query + ";")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con + .prepareStatement(query + Constants.SEMI_COLON)) { outer = pstmt; pstmt.execute(); // sp_executesql pstmt.getMoreResults(); // Make sure handle is updated. 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 27ff3ea44..2b140e109 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 @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.JDBCType; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -42,8 +41,7 @@ public class RegressionTest extends AbstractTest { */ @Test public void testServerCursorPStmt() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { // expected values int numRowsInResult = 1; @@ -111,7 +109,7 @@ public void testServerCursorPStmt() throws SQLException { */ @Test public void testSelectIntoUpdateCount() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try (SQLServerConnection con = (SQLServerConnection) getConnection()) { // Azure does not do SELECT INTO if (!isSqlAzure()) { @@ -153,8 +151,7 @@ public void testUpdateQuery() throws SQLException { assumeTrue("JDBC41".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { String sql; JDBCType[] targets = {JDBCType.INTEGER, JDBCType.SMALLINT}; int rows = 3; @@ -214,8 +211,7 @@ public void testXmlQuery() throws SQLException { assumeTrue("JDBC41".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - try (Connection connection = DriverManager.getConnection(connectionString); - Statement stmt = connection.createStatement()) { + try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); createTable(stmt); @@ -254,8 +250,7 @@ private void createTable(Statement stmt) throws SQLException { @AfterAll public static void terminate() throws SQLException { - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (SQLServerConnection con = (SQLServerConnection) getConnection(); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, 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 240ce6038..63e174ab6 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 @@ -16,7 +16,6 @@ import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -51,6 +50,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.PrepUtil; /** @@ -74,7 +74,7 @@ public class TCAttentionHandling { @BeforeEach public void init() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { con.setAutoCommit(false); try (Statement stmt = con.createStatement()) { try { @@ -92,8 +92,7 @@ public void init() throws Exception { @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} @@ -108,8 +107,7 @@ public void terminate() throws Exception { @Test public void testCancelBeforeExecute() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.cancel(); try (ResultSet rs = stmt .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { @@ -134,9 +132,8 @@ public void testCancelBeforeExecute() throws Exception { */ @Test public void testErrorInRequest() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement ps = con.prepareStatement("UPDATE " - + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col2 = ? WHERE col1 = ?")) { + try (Connection con = getConnection(); 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); @@ -169,7 +166,7 @@ public void testErrorInRequest() throws Exception { public void testQueryTimeout() throws Exception { long elapsedMillis; - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement("WAITFOR DELAY '00:00:07'")) { // First execution: @@ -220,7 +217,7 @@ public void testCancelLongResponse() throws Exception { assumeTrue("JDBC42".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con + try (Connection con = getConnection(); Statement stmt = con .createStatement(SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); @@ -308,7 +305,7 @@ public void testCancelBlockedResponse() throws Exception { Thread oneShotCancel = null; - try (Connection conLock = DriverManager.getConnection(connectionString)) { + try (Connection conLock = getConnection()) { // Start a transaction on a second connection that locks the last part of the table // and leave it non-responsive for now... conLock.setAutoCommit(false); @@ -316,7 +313,7 @@ public void testCancelBlockedResponse() throws Exception { stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col2 = 'New Value!' WHERE col1 = " + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options // are always ON and can NOT be turned OFF. Thus the default transaction isolation level // READ_COMMITTED @@ -400,7 +397,7 @@ public void testCancelBlockedResponsePS() throws Exception { Thread oneShotCancel = null; - try (Connection conLock = DriverManager.getConnection(connectionString)) { + try (Connection conLock = getConnection()) { // Start a transaction on a second connection that locks the last part of the table // and leave it non-responsive for now... conLock.setAutoCommit(false); @@ -408,7 +405,7 @@ public void testCancelBlockedResponsePS() throws Exception { stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col2 = 'New Value!' WHERE col1 = " + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options // are always ON and can NOT be turned OFF. Thus the default transaction isolation level // READ_COMMITTED @@ -495,7 +492,7 @@ public void testCancelBlockedResponsePS() throws Exception { public void testCancelBlockedCursoredResponse() throws Exception { Thread oneShotCancel = null; - try (Connection conLock = DriverManager.getConnection(connectionString)) { + try (Connection conLock = getConnection()) { // Start a transaction on a second connection that locks the last part of the table // and leave it non-responsive for now... conLock.setAutoCommit(false); @@ -503,7 +500,7 @@ public void testCancelBlockedCursoredResponse() throws Exception { stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col2 = 'New Value!' WHERE col1 = " + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options // are always ON and can NOT be turned OFF. Thus the default transaction isolation level // READ_COMMITTED @@ -580,8 +577,7 @@ public void testCancelBlockedCursoredResponse() throws Exception { @Test public void testCancelAfterResponse() throws Exception { int numSelectedRows; - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { try (ResultSet rs = stmt .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { numSelectedRows = 0; @@ -614,7 +610,7 @@ 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. final String procName = RandomUtil.getIdentifier("p1"); - try (Connection con = DriverManager.getConnection(connectionString + ";packetSize=512"); + try (Connection con = PrepUtil.getConnection(connectionString + ";packetSize=512"); Statement stmt = con.createStatement()) { try { @@ -794,7 +790,7 @@ void stop() { // (hammer ID, execute interval, cancel interval) new Hammer(4, 120, 180), new Hammer(3, 60, 184), new Hammer(2, 30, 150), new Hammer(1, 10, 50)}; - final Connection dbCon = DriverManager.getConnection(connectionString); + final Connection dbCon = getConnection(); for (Hammer hammer : hammers) hammer.start(dbCon); @@ -842,8 +838,7 @@ void stop() { @Test public void testIsCloseOnCompletion() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement ps = con.prepareStatement("")) { + try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement("")) { boolean result = false; try { @@ -860,8 +855,7 @@ public void testIsCloseOnCompletion() throws Exception { @Test public void testCloseOnCompletion() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement ps = con.prepareStatement("select ?")) { + try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement("select ?")) { ps.setInt(1, 1); // enable isCloseOnCompletion @@ -896,8 +890,7 @@ public class TCStatement { */ @Test public void testIsCloseOnCompletion() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { assertEquals(false, stmt.isCloseOnCompletion(), "isCloseOnCompletion default should be false."); @@ -918,8 +911,7 @@ public void testIsCloseOnCompletion() throws Exception { */ @Test public void testCloseOnCompletion() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { // enable isCloseOnCompletion try { stmt.closeOnCompletion(); @@ -947,8 +939,7 @@ public void testCloseOnCompletion() throws Exception { */ @Test public void testConsecutiveQueries() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { // enable isCloseOnCompletion try { stmt.closeOnCompletion(); @@ -984,7 +975,7 @@ public void testLargeMaxRowsJDBC41() throws Exception { assumeTrue("JDBC41".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { // testing exception for getLargeMaxRows method @@ -1015,8 +1006,7 @@ public void testLargeMaxRowsJDBC42() throws Exception { assumeTrue("JDBC42".equals(TestUtils.getConfiguredProperty("JDBC_Version")), TestResource.getResource("R_incompatJDBC")); - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { // Default value should return zero long actual = stmt.getLargeMaxRows(); @@ -1057,8 +1047,7 @@ public void testLargeMaxRowsJDBC42() throws Exception { @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement();) { + try (Connection con = getConnection(); Statement stmt = con.createStatement();) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1Name), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); @@ -1080,7 +1069,7 @@ public class TCStatementCallable { public void testJdbc41CallableStatementMethods() throws Exception { // Prepare database setup - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col1Value varchar(512) OUTPUT," + " @col2Value int OUTPUT," + " @col3Value float OUTPUT," @@ -1214,12 +1203,11 @@ public void testJdbc41CallableStatementMethods() throws Exception { @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { try { TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } @@ -1237,8 +1225,7 @@ public class TCStatementParam { */ @Test public void testStatementOutParamGetsTwice() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { // enable isCloseOnCompletion try { @@ -1286,8 +1273,7 @@ public void testStatementOutParamGetsTwice() throws Exception { @Test public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { 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"); @@ -1320,8 +1306,7 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { */ @Test public void testStatementOutParamGetsTwiceInOut() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { 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"); @@ -1350,7 +1335,7 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { */ @Test public void testResultSetParams() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -1385,7 +1370,7 @@ public void testResultSetParams() throws Exception { */ @Test public void testResultSetNullParams() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -1419,8 +1404,7 @@ public void testResultSetNullParams() throws Exception { */ @Test public void testFailedToResumeTransaction() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0)"); @@ -1450,7 +1434,7 @@ public void testFailedToResumeTransaction() throws Exception { */ @Test public void testResultSetErrors() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) @@ -1482,8 +1466,7 @@ public void testResultSetErrors() throws Exception { @Disabled // TODO: We are commenting this out due to random AppVeyor failures. We will investigate later. public void testRowError() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); stmt.executeUpdate("insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0)"); @@ -1506,7 +1489,7 @@ public void testRowError() throws Exception { for (int row = 0; row <= 2; row++) { // On the first connection, retrieve the indicated row, // locking it for update. - try (Connection testConn1 = DriverManager.getConnection(connectionString)) { + try (Connection testConn1 = getConnection()) { testConn1.setAutoCommit(false); try (CallableStatement cstmt = testConn1 .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?)}")) { @@ -1526,7 +1509,7 @@ public void testRowError() throws Exception { // On a second connection, repeat the query, with an immediate // lock timeout to induce an error. - try (Connection testConn2 = DriverManager.getConnection(connectionString)) { + try (Connection testConn2 = getConnection()) { testConn2.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); testConn2.setAutoCommit(false); try (Statement stmt2 = testConn2.createStatement()) { @@ -1574,13 +1557,12 @@ public void testRowError() throws Exception { @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } @@ -1610,12 +1592,11 @@ private Connection createConnectionAndPopulateData() throws Exception { @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } @@ -1930,7 +1911,7 @@ public void testNBCROWWithRandomAccess() throws Exception { public class TCStatementIsClosed { @Test public void testActiveStatement() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { // enable isCloseOnCompletion @@ -1957,7 +1938,7 @@ public void testActiveStatement() throws Exception { */ @Test public void testClosedStatement() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.close(); @@ -1976,7 +1957,7 @@ public void testClosedStatement() throws Exception { */ @Test public void testClosedConnection() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); + try (Connection conn = getConnection(); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { conn.close(); @@ -1999,8 +1980,7 @@ public class TCResultSetIsClosed { */ @Test public void testActiveResultSet() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { // enable isCloseOnCompletion try { @@ -2030,8 +2010,7 @@ public void testActiveResultSet() throws Exception { */ @Test public void testClosedResultSet() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { // enable isCloseOnCompletion try { @@ -2060,8 +2039,7 @@ public void testClosedResultSet() throws Exception { */ @Test public void testClosedStatement() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1")) { stmt.close(); @@ -2082,8 +2060,7 @@ public void testClosedStatement() throws Exception { */ @Test public void testClosedConnection() throws Exception { - try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement()) { + try (Connection conn = getConnection(); Statement stmt = conn.createStatement()) { try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT 1")) { conn.close(); @@ -2109,7 +2086,7 @@ public class TCUpdateCountWithTriggers { @BeforeEach public void setup() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { con.setAutoCommit(false); try (Statement stmt = con.createStatement()) { @@ -2158,7 +2135,7 @@ public void setup() throws Exception { @Test public void testLastUpdateCountTrue() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); + try (Connection con = PrepUtil.getConnection(connectionString + ";lastUpdateCount=true"); PreparedStatement ps = con.prepareStatement( "DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 = ?")) { ps.setInt(1, 1); @@ -2178,7 +2155,7 @@ public void testLastUpdateCountTrue() throws Exception { @Test public void testLastUpdateCountFalse() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=false"); + try (Connection con = PrepUtil.getConnection(connectionString + ";lastUpdateCount=false"); PreparedStatement ps = con.prepareStatement( "DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 = ?")) { ps.setInt(1, 1); @@ -2198,7 +2175,7 @@ public void testLastUpdateCountFalse() throws Exception { @Test public void testPreparedStatementInsertExecInsert() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); + try (Connection con = PrepUtil.getConnection(connectionString + ";lastUpdateCount=true"); PreparedStatement ps = con.prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1) VALUES (" + (NUM_ROWS + 1) + "); " + "EXEC " + AbstractSQLGenerator.escapeIdentifier(sprocName) + "; " + "UPDATE " @@ -2220,7 +2197,7 @@ public void testPreparedStatementInsertExecInsert() throws Exception { @Test public void testStatementInsertExecInsert() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); + try (Connection con = PrepUtil.getConnection(connectionString + ";lastUpdateCount=true"); Statement stmt = con.createStatement()) { int updateCount = stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1) VALUES (" + (NUM_ROWS + 1) + "); " + "EXEC " @@ -2235,14 +2212,13 @@ public void testStatementInsertExecInsert() throws Exception { @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement();) { + try (Connection con = getConnection(); Statement stmt = con.createStatement();) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(sprocName), stmt); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } @@ -2257,17 +2233,10 @@ public class TCUpdateCountAfterRaiseError { @BeforeEach public void setup() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { con.setAutoCommit(false); try (Statement stmt = con.createStatement()) { - - try { - 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()); - } + TestUtils.dropTriggerIfExists(triggerName, stmt); stmt.executeUpdate( "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 INT )"); for (int i = 0; i < NUM_ROWS; i++) @@ -2277,7 +2246,7 @@ public void setup() throws Exception { // Skip adding message for 50001 if the target server is SQL Azure, because SQL Azure does not // support // sp_addmessage. - try (Connection dbConn = DriverManager.getConnection(connectionString)) { + try (Connection dbConn = getConnection()) { if (isSqlAzure()) { log.fine( "Because SQL Azure does not support sp_addmessage, 'EXEC sp_addmessage ...' is skipped."); @@ -2306,7 +2275,7 @@ public void setup() throws Exception { @Test public void testUpdateCountAfterRaiseError() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); + try (Connection con = getConnection(); PreparedStatement pstmt = con .prepareStatement("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col1 = 5 WHERE col1 = 2 RAISERROR(50001, 17, 1) SELECT * FROM " @@ -2362,7 +2331,7 @@ public void testUpdateCountAfterRaiseError() throws Exception { @Test public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = false"); + try (Connection con = PrepUtil.getConnection(connectionString + ";lastUpdateCount = false"); PreparedStatement pstmt = con.prepareStatement( "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (5)")) { @@ -2411,7 +2380,7 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exce @Test public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); + try (Connection con = PrepUtil.getConnection(connectionString + ";lastUpdateCount = true"); PreparedStatement pstmt = con.prepareStatement( "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (5)")) { @@ -2454,12 +2423,11 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Excep @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement();) { + try (Connection con = getConnection(); Statement stmt = con.createStatement();) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } @@ -2473,7 +2441,7 @@ public class TCNocount { @BeforeEach public void setup() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString)) { + try (Connection con = getConnection()) { con.setAutoCommit(false); try (Statement stmt = con.createStatement()) { @@ -2503,7 +2471,7 @@ public void setup() throws Exception { @Test public void testNoCountWithExecute() throws Exception { // Ensure lastUpdateCount=true... - try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); + try (Connection con = PrepUtil.getConnection(connectionString + ";lastUpdateCount = true"); Statement stmt = con.createStatement();) { boolean isResultSet = stmt @@ -2526,12 +2494,11 @@ public void testNoCountWithExecute() throws Exception { @AfterEach public void terminate() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); - Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { try { TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { - fail(e.toString()); + fail(e.getMessage()); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java index 28ce53717..d877c21c0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/WrapperTest.java @@ -9,7 +9,6 @@ import java.sql.CallableStatement; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.text.MessageFormat; @@ -42,78 +41,75 @@ public class WrapperTest extends AbstractTest { */ @Test public void wrapTest() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); MessageFormat form = new MessageFormat(TestResource.getResource("R_shouldBeWrapper")); MessageFormat form2 = new MessageFormat(TestResource.getResource("R_shouldNotBeWrapper")); Object[][] msgArgs = {{"SQLStatement", "self"}, {"SQLServerStatement", "ISQLServerStatement"}, {"SQLServerCallableStatement", "SQLServerStatement"}, {"SQLServerCallableStatement", "SQLServerStatement"}}; - try (Connection con = DriverManager.getConnection(connectionString)) { - try (Statement stmt = con.createStatement()) { + try (Connection con = getConnection(); Statement stmt = con.createStatement()) { - // First make sure that a statement can be unwrapped - boolean isWrapper = ((SQLServerStatement) stmt) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); + // First make sure that a statement can be unwrapped + boolean isWrapper = ((SQLServerStatement) stmt) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[0])); + assertEquals(isWrapper, true, form.format(msgArgs[0])); - isWrapper = ((SQLServerStatement) stmt) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[1])); + isWrapper = ((SQLServerStatement) stmt) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[1])); - isWrapper = ((SQLServerStatement) stmt) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerConnection")); - assertEquals(isWrapper, false, form2.format(msgArgs[1])); + isWrapper = ((SQLServerStatement) stmt) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerConnection")); + assertEquals(isWrapper, false, form2.format(msgArgs[1])); - // Now make sure that we can unwrap a SQLServerCallableStatement to a SQLServerStatement - try (CallableStatement cs = con.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }")) { - // Test the class first + // Now make sure that we can unwrap a SQLServerCallableStatement to a SQLServerStatement + try (CallableStatement cs = con.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }")) { + // Test the class first + isWrapper = ((SQLServerCallableStatement) cs) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[2])); + // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and make + // sure it succeeds. + try (SQLServerStatement stmt2 = (SQLServerStatement) ((SQLServerCallableStatement) cs) + .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement"))) { + stmt2.setResponseBuffering("adaptive"); + + // now test the interface isWrapper = ((SQLServerCallableStatement) cs) - .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[2])); - // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and make - // sure it succeeds. - try (SQLServerStatement stmt2 = (SQLServerStatement) ((SQLServerCallableStatement) cs) - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerStatement"))) { - stmt2.setResponseBuffering("adaptive"); - - // now test the interface - isWrapper = ((SQLServerCallableStatement) cs).isWrapperFor( - Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerCallableStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[1])); - - // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and - // make sure it succeeds. - try (ISQLServerPreparedStatement stmt3 = (ISQLServerPreparedStatement) ((SQLServerCallableStatement) cs) - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerPreparedStatement"))) { - stmt3.setResponseBuffering("adaptive"); - - if (isKatmaiServer()) - stmt3.setDateTimeOffset(1, null); - - // Try Unwrapping CallableStatement to a callableStatement - isWrapper = ((SQLServerCallableStatement) cs).isWrapperFor( - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement")); - assertEquals(isWrapper, true, form.format(msgArgs[3])); - // Now unwrap the Callable to a SQLServerCallableStatement and call a SQLServerStatement - // specific function and make sure it succeeds. - try (SQLServerCallableStatement stmt4 = (SQLServerCallableStatement) ((SQLServerCallableStatement) cs) - .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement"))) { - stmt4.setResponseBuffering("adaptive"); - if (isKatmaiServer()) { - stmt4.setDateTimeOffset(1, null); - } + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerCallableStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[1])); + + // Now unwrap the Callable to a statement and call a SQLServerStatement specific function and + // make sure it succeeds. + try (ISQLServerPreparedStatement stmt3 = (ISQLServerPreparedStatement) ((SQLServerCallableStatement) cs) + .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerPreparedStatement"))) { + stmt3.setResponseBuffering("adaptive"); + + if (isKatmaiServer()) + stmt3.setDateTimeOffset(1, null); + + // Try Unwrapping CallableStatement to a callableStatement + isWrapper = ((SQLServerCallableStatement) cs) + .isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement")); + assertEquals(isWrapper, true, form.format(msgArgs[3])); + // Now unwrap the Callable to a SQLServerCallableStatement and call a SQLServerStatement + // specific function and make sure it succeeds. + try (SQLServerCallableStatement stmt4 = (SQLServerCallableStatement) ((SQLServerCallableStatement) cs) + .unwrap(Class.forName("com.microsoft.sqlserver.jdbc.SQLServerCallableStatement"))) { + stmt4.setResponseBuffering("adaptive"); + if (isKatmaiServer()) { + stmt4.setDateTimeOffset(1, null); } } } } - } catch (UnsupportedOperationException e) { - assertEquals(System.getProperty("java.specification.version"), "1.5", - "isWrapperFor " + TestResource.getResource("R_shouldBeSupported")); - assertTrue(e.getMessage().equalsIgnoreCase("This operation is not supported."), - TestResource.getResource("R_unexpectedExceptionContent")); } + } catch (UnsupportedOperationException e) { + assertEquals(System.getProperty("java.specification.version"), "1.5", + "isWrapperFor " + TestResource.getResource("R_shouldBeSupported")); + assertTrue(e.getMessage().equalsIgnoreCase("This operation is not supported."), + TestResource.getResource("R_unexpectedExceptionContent")); } } @@ -124,9 +120,7 @@ public void wrapTest() throws Exception { */ @Test public void unWrapFailureTest() throws Exception { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); - try (Connection con = DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + try (Connection con = getConnection(); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String str = "java.lang.String"; boolean isWrapper = stmt.isWrapperFor(Class.forName(str)); stmt.unwrap(Class.forName(str)); @@ -135,7 +129,7 @@ public void unWrapFailureTest() throws Exception { assertTrue(false, TestResource.getResource("R_exceptionNotThrown")); } catch (SQLException ex) { Throwable t = ex.getCause(); - Class exceptionClass = Class.forName("java.lang.ClassCastException"); + Class exceptionClass = Class.forName("java.lang.ClassCastException"); assertEquals(t.getClass(), exceptionClass, "The cause in the exception class does not match"); } catch (UnsupportedOperationException e) { assertEquals(System.getProperty("java.specification.version"), "1.5", diff --git a/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java b/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java index 042ca2700..7493b4267 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/AbstractSQLGenerator.java @@ -11,36 +11,17 @@ /** * Common methods needed for any implementation for {@link SQLGeneratorIF} */ -public abstract class AbstractSQLGenerator {// implements ISQLGenerator { +public abstract class AbstractSQLGenerator extends Constants {// implements ISQLGenerator { - protected static final String CREATE_TABLE = "CREATE TABLE"; - protected static final String SPACE_CHAR = " "; - protected static final String OPEN_BRACKET = "("; - protected static final String CLOSE_BRACKET = ")"; - protected static final String NOT = "NOT"; - protected static final String NULL = "NULL"; - protected static final String PRIMARY_KEY = "PRIMARY KEY"; - protected static final String DEFAULT = "DEFAULT"; - protected static final String COMMA = ","; - protected static final String QUESTION_MARK = "?"; - protected static final String SEMI_COLON = ";"; - - // FIXME: Find good word for '. Better replaced by wrapIdentifier. - protected static final String TICK = "'"; - - protected static final String defaultWrapIdentifier = "\'"; - - protected static String wrapIdentifier = defaultWrapIdentifier; - - protected static String openEscapeIdentifier = "["; - - protected static String closeEscapeIdentifier = "]"; + static String WRAP_IDENTIFIER = DEFAULT_WRAP_IDENTIFIER; + static String OPEN_ESCAPE_IDENTIFIER = "["; + static String CLOSE_ESCAPE_IDENTIFIER = "]"; /** * @return the wrapIdentifier */ public static String getWrapIdentifier() { - return wrapIdentifier; + return WRAP_IDENTIFIER; } /** @@ -48,7 +29,7 @@ public static String getWrapIdentifier() { * the wrapIdentifier to set */ public static void setWrapIdentifier(String wrapIdentifier) { - AbstractSQLGenerator.wrapIdentifier = wrapIdentifier; + AbstractSQLGenerator.WRAP_IDENTIFIER = wrapIdentifier; } // TODO: should provide more detail to distinguish between wrap and escape @@ -74,8 +55,8 @@ public String wrapName(String name) { * @param closeIdentifier */ public static void setEscapeIdentifier(String openIdentifier, String closeIdentifier) { - AbstractSQLGenerator.openEscapeIdentifier = openIdentifier; - AbstractSQLGenerator.closeEscapeIdentifier = closeIdentifier; + AbstractSQLGenerator.OPEN_ESCAPE_IDENTIFIER = openIdentifier; + AbstractSQLGenerator.CLOSE_ESCAPE_IDENTIFIER = closeIdentifier; } /** @@ -85,7 +66,7 @@ public static void setEscapeIdentifier(String openIdentifier, String closeIdenti * @return escaped literal */ public static String escapeIdentifier(String value) { - return openEscapeIdentifier + value + closeEscapeIdentifier; + return OPEN_ESCAPE_IDENTIFIER + value + CLOSE_ESCAPE_IDENTIFIER; } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java b/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java index 6e3f7c32f..6c77881c7 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java @@ -10,7 +10,6 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; -import java.util.concurrent.ThreadLocalRandom; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Handler; @@ -28,6 +27,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.SQLServerDriver; import com.microsoft.sqlserver.jdbc.SQLServerXADataSource; +import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; @@ -42,17 +42,13 @@ */ public abstract class AbstractTest { - protected static final Logger logger = Logger.getLogger("AbstractTest"); - protected static final ThreadLocalRandom random = ThreadLocalRandom.current(); - protected static final String secretstrJks = "changeit"; + static String applicationClientID = null; + static String applicationKey = null; + static String[] keyIDs = null; - protected static String applicationClientID = null; - protected static String applicationKey = null; - protected static String[] keyIDs = null; - - protected static String[] jksPaths = null; - protected static String[] javaKeyAliases = null; - protected static String windowsKeyPath = null; + static String[] jksPaths = null; + static String[] javaKeyAliases = null; + static String windowsKeyPath = null; protected static SQLServerConnection connection = null; protected static ISQLServerDataSource ds = null; @@ -60,13 +56,9 @@ public abstract class AbstractTest { protected static ISQLServerDataSource dsPool = null; protected static Connection connectionAzure = null; - protected static String connectionString = null; - protected static Properties info = new Properties(); - private final static int ENGINE_EDITION_FOR_SQL_AZURE = 5; - private final static int ENGINE_EDITION_FOR_SQL_AZURE_DW = 6; private static boolean _determinedSqlAzureOrSqlServer = false; private static boolean _isSqlAzure = false; private static boolean _isSqlAzureDW = false; @@ -83,27 +75,28 @@ public static void setup() throws Exception { applicationClientID = getConfiguredProperty("applicationClientID"); applicationKey = getConfiguredProperty("applicationKey"); - keyIDs = getConfiguredProperty("keyID", "").split(";"); + keyIDs = getConfiguredProperty("keyID", "").split(Constants.SEMI_COLON); - connectionString = getConfiguredProperty("mssql_jdbc_test_connection_properties"); + connectionString = getConfiguredProperty(Constants.MSSQL_JDBC_TEST_CONNECTION_PROPERTIES); ds = updateDataSource(new SQLServerDataSource()); dsXA = updateDataSource(new SQLServerXADataSource()); dsPool = updateDataSource(new SQLServerConnectionPoolDataSource()); - jksPaths = getConfiguredProperty("jksPaths", "").split(";"); - javaKeyAliases = getConfiguredProperty("javaKeyAliases", "").split(";"); + jksPaths = getConfiguredProperty("jksPaths", "").split(Constants.SEMI_COLON); + javaKeyAliases = getConfiguredProperty("javaKeyAliases", "").split(Constants.SEMI_COLON); windowsKeyPath = getConfiguredProperty("windowsKeyPath"); // info.setProperty("ColumnEncryptionSetting", "Enabled"); // May be we // can use parameterized way to change this value if (!jksPaths[0].isEmpty()) { - info.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); + info.setProperty("keyStoreAuthentication", Constants.JAVA_KEY_STORE_PASSWORD); info.setProperty("keyStoreLocation", jksPaths[0]); - info.setProperty("keyStoreSecret", secretstrJks); + info.setProperty("keyStoreSecret", Constants.JKS_SECRET_STRING); } try { - Assertions.assertNotNull(connectionString, "Connection String should not be null"); + Assertions.assertNotNull(connectionString, TestResource.getResource("R_ConnectionStringNull")); + Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerDriver"); connection = PrepUtil.getConnection(connectionString, info); isSqlAzureOrAzureDW(connection); } catch (Exception e) { @@ -119,63 +112,65 @@ public static void setup() throws Exception { * DataSource to be configured * @return ISQLServerDataSource */ - private static ISQLServerDataSource updateDataSource(ISQLServerDataSource ds) { - String prefix = "jdbc:sqlserver://"; - if (null != connectionString && connectionString.startsWith(prefix)) { - String extract = connectionString.substring(prefix.length()); - String[] identifiers = extract.split(";"); + protected static ISQLServerDataSource updateDataSource(ISQLServerDataSource ds) { + if (null != connectionString && connectionString.startsWith(Constants.JDBC_PREFIX)) { + String extract = connectionString.substring(Constants.JDBC_PREFIX.length()); + String[] identifiers = extract.split(Constants.SEMI_COLON); String server = identifiers[0]; + // Check if serverName contains instance name - if (server.contains("\\")) { - int i = identifiers[0].indexOf('\\'); + if (server.contains(Constants.BACK_SLASH)) { + int i = identifiers[0].indexOf(Constants.BACK_SLASH); ds.setServerName(extractPort(server.substring(0, i), ds)); ds.setInstanceName(server.substring(i + 1)); } else { ds.setServerName(extractPort(server, ds)); } for (String prop : identifiers) { - if (prop.contains("=")) { - int index = prop.indexOf("="); + if (prop.contains(Constants.EQUAL_TO)) { + int index = prop.indexOf(Constants.EQUAL_TO); String name = prop.substring(0, index); String value = prop.substring(index + 1); switch (name.toUpperCase()) { - case "USER": - case "USERNAME": + case Constants.INTEGRATED_SECURITY: + ds.setIntegratedSecurity(Boolean.parseBoolean(value)); + case Constants.USER: + case Constants.USER_NAME: ds.setUser(value); break; - case "PORT": - case "PORTNUMBER": + case Constants.PORT: + case Constants.PORT_NUMBER: ds.setPortNumber(Integer.parseInt(value)); break; - case "PASSWORD": + case Constants.PASSWORD: ds.setPassword(value); break; - case "DATABASE": - case "DATABASENAME": + case Constants.DATABASE: + case Constants.DATABASE_NAME: ds.setDatabaseName(value); break; - case "COLUMNENCRYPTIONSETTING": + case Constants.COLUMN_ENCRYPTION_SETTING: ds.setColumnEncryptionSetting(value); break; - case "DISABLESTATEMENTPOOLING": + case Constants.DISABLE_STATEMENT_POOLING: ds.setDisableStatementPooling(Boolean.parseBoolean(value)); break; - case "STATEMENTPOOLINGCACHESIZE": + case Constants.STATEMENT_POOLING_CACHE_SIZE: ds.setStatementPoolingCacheSize(Integer.parseInt(value)); break; - case "AUTHENTICATION": + case Constants.AUTHENTICATION: ds.setAuthentication(value); break; - case "AUTHENTICATIONSCHEME": + case Constants.AUTHENTICATION_SCHEME: ds.setAuthenticationScheme(value); break; - case "CANCELQUERYTIMEOUT": + case Constants.CANCEL_QUERY_TIMEOUT: ds.setCancelQueryTimeout(Integer.parseInt(value)); break; - case "ENCRYPT": + case Constants.ENCRYPT: ds.setEncrypt(Boolean.parseBoolean(value)); break; - case "HOSTNAMEINCERTIFICATE": + case Constants.HOST_NAME_IN_CERTIFICATE: ds.setHostNameInCertificate(value); break; default: @@ -188,9 +183,9 @@ private static ISQLServerDataSource updateDataSource(ISQLServerDataSource ds) { } static String extractPort(String server, ISQLServerDataSource ds) { - if (server.contains(":")) { - ds.setPortNumber(Integer.parseInt(server.substring(server.indexOf(":") + 1))); - server = server.substring(0, server.indexOf(":")); + if (server.contains(Constants.COLON)) { + ds.setPortNumber(Integer.parseInt(server.substring(server.indexOf(Constants.COLON) + 1))); + server = server.substring(0, server.indexOf(Constants.COLON)); } return server; } @@ -204,6 +199,16 @@ public static String getConnectionString() { return connectionString; } + /** + * Retrieves connection using default configured connection string + * + * @return + * @throws SQLException + */ + protected static SQLServerConnection getConnection() throws SQLException { + return PrepUtil.getConnection(connectionString); + } + /** * This will take care of all clean ups after running the Test Suite. * @@ -253,33 +258,32 @@ public static String getConfiguredProperty(String key, String defaultValue) { public static void invokeLogging() { Handler handler = null; - String enableLogging = getConfiguredProperty("mssql_jdbc_logging", "false"); + String enableLogging = getConfiguredProperty(Constants.MSSQL_JDBC_LOGGING, Boolean.FALSE.toString()); // If logging is not enable then return. - if (!"true".equalsIgnoreCase(enableLogging)) { + if (!Boolean.TRUE.toString().equalsIgnoreCase(enableLogging)) { return; } - String loggingHandler = getConfiguredProperty("mssql_jdbc_logging_handler", "not_configured"); + String loggingHandler = getConfiguredProperty(Constants.MSSQL_JDBC_LOGGING_HANDLER, "not_configured"); try { - // handler = new FileHandler("Driver.log"); - if ("console".equalsIgnoreCase(loggingHandler)) { + if (Constants.LOGGING_HANDLER_CONSOLE.equalsIgnoreCase(loggingHandler)) { handler = new ConsoleHandler(); - } else if ("file".equalsIgnoreCase(loggingHandler)) { - handler = new FileHandler("Driver.log"); + } else if (Constants.LOGGING_HANDLER_FILE.equalsIgnoreCase(loggingHandler)) { + handler = new FileHandler(Constants.DEFAULT_DRIVER_LOG); System.out.println("Look for Driver.log file in your classpath for detail logs"); } if (handler != null) { handler.setFormatter(new SimpleFormatter()); handler.setLevel(Level.FINEST); - Logger.getLogger("").addHandler(handler); + Logger.getLogger(Constants.MSSQL_JDBC_LOGGING_HANDLER).addHandler(handler); } // By default, Loggers also send their output to their parent logger. // Typically the root Logger is configured with a set of Handlers that essentially act as default handlers // for all loggers. - Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc"); + Logger logger = Logger.getLogger(Constants.MSSQL_JDBC_PACKAGE); logger.setLevel(Level.FINEST); } catch (Exception e) { System.err.println("Some how could not invoke logging: " + e.getMessage()); @@ -311,9 +315,9 @@ private static void isSqlAzureOrAzureDW(Connection con) throws SQLException { ResultSet rs = stmt.executeQuery("SELECT CAST(SERVERPROPERTY('EngineEdition') as INT)")) { rs.next(); int engineEdition = rs.getInt(1); - _isSqlAzure = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE - || engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_DW); - _isSqlAzureDW = (engineEdition == ENGINE_EDITION_FOR_SQL_AZURE_DW); + _isSqlAzure = (engineEdition == Constants.ENGINE_EDITION_FOR_SQL_AZURE + || engineEdition == Constants.ENGINE_EDITION_FOR_SQL_AZURE_DW); + _isSqlAzureDW = (engineEdition == Constants.ENGINE_EDITION_FOR_SQL_AZURE_DW); _determinedSqlAzureOrSqlServer = true; } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/Constants.java b/src/test/java/com/microsoft/sqlserver/testframework/Constants.java new file mode 100644 index 000000000..677173507 --- /dev/null +++ b/src/test/java/com/microsoft/sqlserver/testframework/Constants.java @@ -0,0 +1,114 @@ +package com.microsoft.sqlserver.testframework; + +import java.sql.Date; +import java.time.LocalDateTime; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.logging.Logger; + +import com.microsoft.sqlserver.jdbc.RandomUtil; + + +public class Constants { + public static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current(); + public static final Logger LOGGER = Logger.getLogger("AbstractTest"); + public static final String JKS_SECRET_STRING = "changeit"; + public static final String JDBC_PREFIX = "jdbc:sqlserver://"; + public static final String DEFAULT_DRIVER_LOG = "Driver.log"; + public static final String MSSQL_JDBC_PACKAGE = "com.microsoft.sqlserver.jdbc"; + + public static final String DEFAULT_WRAP_IDENTIFIER = "\'"; + public static final String CREATE_TABLE = "CREATE TABLE"; + public static final String SPACE_CHAR = " "; + public static final String OPEN_BRACKET = "("; + public static final String CLOSE_BRACKET = ")"; + public static final String NOT = "NOT"; + public static final String NULL = "NULL"; + public static final String PRIMARY_KEY = "PRIMARY KEY"; + public static final String DEFAULT = "DEFAULT"; + public static final String COMMA = ","; + public static final String QUESTION_MARK = "?"; + public static final String SINGLE_QUOTE = "'"; + public static final String SEMI_COLON = ";"; + public static final String COLON = ":"; + public static final String EQUAL_TO = "="; + public static final String BACK_SLASH = "\\"; + + public static final String ENABLED = "Enabled"; + + // Environment properties + public static final String FIPS_ENV = "FIPS_ENV"; + public static final String MSSQL_JDBC_TEST_CONNECTION_PROPERTIES = "mssql_jdbc_test_connection_properties"; + public static final String MSSQL_JDBC_LOGGING = "mssql_jdbc_logging"; + public static final String MSSQL_JDBC_LOGGING_HANDLER = "mssql_jdbc_logging_handler"; + + public static final String LOGGING_HANDLER_FILE = "file"; + public static final String LOGGING_HANDLER_CONSOLE = "console"; + + public final static int ENGINE_EDITION_FOR_SQL_AZURE = 5; + public final static int ENGINE_EDITION_FOR_SQL_AZURE_DW = 6; + + public static final Date DATE = new Date(new java.util.Date().getTime()); + public static final LocalDateTime NOW = LocalDateTime.now(); + + public static final int LOB_ARRAY_SIZE = 500; // number of rows to insert into the table and compare + public static final int LOB_LENGTH_MIN = 8000; + public static final int LOB_LENGTH_MAX = 32000; + public static final String ASCII_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+,./;'[]<>?:{}|`~\"\\"; + public static final String UNICODE_CHARACTERS = ASCII_CHARACTERS + + "Ǥ⚌c♮ƺåYèĢù⚏Ȓ★njäõpƸŃōoƝĤßuÙőƆE♹gLJÜŬȺDZ!Û☵ŦãǁĸNQŰǚǻTÖC]ǶýåÉbɉ☩=\\ȍáźŗǃĻýű☓☄¸T☑ö^k☏I:x☑⚀läiȉ☱☚⚅ǸǎãÂ"; + + // AE Constants + public static final String JAVA_KEY_STORE_FILENAME = "JavaKeyStore.txt"; + public static final String JAVA_KEY_STORE_NAME = "MSSQL_JAVA_KEYSTORE"; + public static final String JAVA_KEY_STORE_PASSWORD = "JavaKeyStorePassword"; + public static final String JKS = "JKS"; + public static final String JKS_NAME = "clientcert.jks"; + public static final String JKS_SECRET = "password"; + public static final String PKCS12 = "PKCS12"; + + public static final String UID = UUID.randomUUID().toString(); + public static final Long RANDOM_LONG = Long.valueOf((long) (RANDOM.nextDouble() * Math.pow(10, 10))); + public static final String CMK_NAME = "JDBC_CMK_" + RANDOM_LONG; + public static final String CEK_NAME = "JDBC_CEK_" + RANDOM_LONG; + public static final String CEK_ALGORITHM = "RSA_OAEP"; + public static final String CEK_STRING = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + public static final String CHAR_TABLE_AE = RandomUtil.getIdentifier("JDBCEncryptedChar"); + public static final String BINARY_TABLE_AE = RandomUtil.getIdentifier("JDBCEncryptedBinary"); + public static final String DATE_TABLE_AE = RandomUtil.getIdentifier("JDBCEncryptedDate"); + public static final String NUMERIC_TABLE_AE = RandomUtil.getIdentifier("JDBCEncryptedNumeric"); + public static final String SCALE_DATE_TABLE_AE = RandomUtil.getIdentifier("JDBCEncryptedScaleDate"); + + // Start: Connection Properties parsed in AbstractTest class for creating DataSource. + public static final String INTEGRATED_SECURITY = "INTEGRATEDSECURITY"; + public static final String USER = "USER"; + public static final String USER_NAME = "USERNAME"; + public static final String PORT = "PORT"; + public static final String PORT_NUMBER = "PORTNUMBER"; + public static final String PASSWORD = "PASSWORD"; + public static final String DATABASE = "DATABASE"; + public static final String DATABASE_NAME = "DATABASENAME"; + public static final String COLUMN_ENCRYPTION_SETTING = "COLUMNENCRYPTIONSETTING"; + public static final String DISABLE_STATEMENT_POOLING = "DISABLESTATEMENTPOOLING"; + public static final String STATEMENT_POOLING_CACHE_SIZE = "STATEMENTPOOLINGCACHESIZE"; + public static final String AUTHENTICATION = "AUTHENTICATION"; + public static final String AUTHENTICATION_SCHEME = "AUTHENTICATIONSCHEME"; + public static final String CANCEL_QUERY_TIMEOUT = "CANCELQUERYTIMEOUT"; + public static final String ENCRYPT = "ENCRYPT"; + public static final String HOST_NAME_IN_CERTIFICATE = "HOSTNAMEINCERTIFICATE"; + // End: Connection Properties parsed in AbstractTest class for creating DataSource. + + // Other Connection Properties set in FipsTest + public static final String FIPS = "FIPS"; + public static final String TRUST_STORE_TYPE = "TRUSTSTORETYPE"; + public static final String TRUST_SERVER_CERTIFICATE = "TRUSTSERVERCERTIFICATE"; + public static final String TRUST_STORE_PASSWORD = "TRUSTSTOREPASSWORD"; + public static final String TRUST_STORE = "TRUSTSTORE"; + + public static enum LOB { + CLOB, + NCLOB, + BLOB + }; +} diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBCallableStatement.java b/src/test/java/com/microsoft/sqlserver/testframework/DBCallableStatement.java index adff2fa7f..2d2af08f4 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBCallableStatement.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBCallableStatement.java @@ -32,7 +32,6 @@ public DBCallableStatement(DBConnection dbconnection) { */ DBCallableStatement(AbstractParentWrapper parent, Object internal, String name) { super(parent, internal, name); - // TODO Auto-generated constructor stub } DBCallableStatement prepareCall(String query) throws SQLException { diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBCoercion.java b/src/test/java/com/microsoft/sqlserver/testframework/DBCoercion.java index c0c673478..6af641e69 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBCoercion.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBCoercion.java @@ -8,31 +8,16 @@ public class DBCoercion { - Class type = null; + Class type = null; protected BitSet flags = new BitSet(); protected String name = null; - // Flags - - public static final int GET = 1; - public static final int UPDATE = 2; - public static final int SET = 3; - public static final int SETOBJECT = 4; - public static final int REG = 5; - public static final int GETPARAM = 6; - public static final int UPDATEOBJECT = 7; - public static final int ALL = 8; - - public static final int STREAM = 9; - public static final int CHAR = 10; - public static final int NCHAR = 11; - public static final int ASCII = 12; /** * * @param type */ - public DBCoercion(Class type) { - this(type, new int[] {GET}); + public DBCoercion(Class type) { + this(type, new int[] {DBConstants.GET_COERCION}); } /** @@ -40,7 +25,7 @@ public DBCoercion(Class type) { * @param type * @param tempflags */ - public DBCoercion(Class type, int[] tempflags) { + public DBCoercion(Class type, int[] tempflags) { name = type.toString(); this.type = type; for (int tempflag : tempflags) @@ -50,7 +35,7 @@ public DBCoercion(Class type, int[] tempflags) { /** * @return type */ - public Class type() { + public Class type() { return type; } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java index d03f264a8..ef779e597 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java @@ -37,7 +37,7 @@ public class DBConnection extends AbstractParentWrapper implements AutoCloseable private PooledConnection pooledConnection = null; /** - * establishes connection using the input + * DBConnection Constructor using provided connection string * * @param connectionString */ @@ -46,6 +46,11 @@ public DBConnection(String connectionString) { getConnection(connectionString); } + /** + * DBConnection Constructor using provided Connection object + * + * @param connection + */ public DBConnection(Connection connection) { super(null, null, "connection"); this.connection = connection; @@ -53,9 +58,9 @@ public DBConnection(Connection connection) { } /** - * establishes connection using the input + * DBConnection Constructor using provided DataSource * - * @param connectionString + * @param dataSource */ public DBConnection(ISQLServerDataSource dataSource) { super(null, null, "connection"); @@ -63,7 +68,7 @@ public DBConnection(ISQLServerDataSource dataSource) { } /** - * establish connection + * Creates connection instance using the connection string provided. * * @param connectionString */ @@ -73,15 +78,13 @@ void getConnection(String connectionString) { setInternal(connection); } catch (SQLException ex) { fail(ex.getMessage()); - } catch (ClassNotFoundException ex) { - fail(ex.getMessage()); } } /** - * establish connection + * Creates connection instance based on the provided DataSource * - * @param connectionString + * @param dataSource */ void getConnection(ISQLServerDataSource dataSource) { try { @@ -233,12 +236,8 @@ public DBCallableStatement prepareCall(String query) throws SQLException { */ public double getServerVersion() throws Exception { if (0 == serverversion) { - DBStatement stmt = null; - DBResultSet rs = null; - - try { - stmt = this.createStatement(DBResultSet.TYPE_DIRECT_FORWARDONLY, ResultSet.CONCUR_READ_ONLY); - rs = stmt.executeQuery("SELECT @@VERSION"); + try (DBStatement stmt = this.createStatement(DBConstants.RESULTSET_TYPE_DIRECT_FORWARDONLY, + ResultSet.CONCUR_READ_ONLY); DBResultSet rs = stmt.executeQuery("SELECT @@VERSION")) { rs.next(); String version = rs.getString(1); @@ -254,9 +253,6 @@ public double getServerVersion() throws Exception { } } catch (Exception e) { throw new Exception("Unable to get dbms major version", e); - } finally { - rs.close(); - stmt.close(); } } return serverversion; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBConstants.java b/src/test/java/com/microsoft/sqlserver/testframework/DBConstants.java new file mode 100644 index 000000000..3ff3a18bd --- /dev/null +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBConstants.java @@ -0,0 +1,38 @@ +package com.microsoft.sqlserver.testframework; + +import java.sql.ResultSet; + + +public class DBConstants { + + // Coercion Flags + public static final int GET_COERCION = 1; + public static final int UPDATE_COERCION = 2; + public static final int SET_COERCION = 3; + public static final int SETOBJECT_COERCION = 4; + public static final int REG_COERCION = 5; + public static final int GETPARAM_COERCION = 6; + public static final int UPDATEOBJECT_COERCION = 7; + public static final int ALL_COERCION = 8; + public static final int STREAM_COERCION = 9; + public static final int CHAR_COERCION = 10; + public static final int NCHAR_COERCION = 11; + public static final int ASCII_COERCION = 12; + + // ResultSet Flags + public static final int RESULTSET_TYPE_DYNAMIC = ResultSet.TYPE_SCROLL_SENSITIVE + 1; + public static final int RESULTSET_CONCUR_OPTIMISTIC = ResultSet.CONCUR_UPDATABLE + 2; + public static final int RESULTSET_TYPE_CURSOR_FORWARDONLY = ResultSet.TYPE_FORWARD_ONLY + 1001; + public static final int RESULTSET_TYPE_FORWARD_ONLY = ResultSet.TYPE_FORWARD_ONLY; + public static final int RESULTSET_CONCUR_READ_ONLY = ResultSet.CONCUR_READ_ONLY; + public static final int RESULTSET_TYPE_SCROLL_INSENSITIVE = ResultSet.TYPE_SCROLL_INSENSITIVE; + public static final int RESULTSET_TYPE_SCROLL_SENSITIVE = ResultSet.TYPE_SCROLL_SENSITIVE; + public static final int RESULTSET_CONCUR_UPDATABLE = ResultSet.CONCUR_UPDATABLE; + public static final int RESULTSET_TYPE_DIRECT_FORWARDONLY = ResultSet.TYPE_FORWARD_ONLY + 1000; + + // Statement Flags + public static final int STATEMENT = 0; + public static final int PREPAREDSTATEMENT = 1; + public static final int CALLABLESTATEMENT = 2; + public static final int ALL_STATEMENTS = 3; +} diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java index 08717c58c..79d25a747 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java @@ -26,7 +26,7 @@ /** - * wrapper class for ResultSet + * wrapper Class for ResultSet * * @author Microsoft * @@ -39,16 +39,6 @@ public class DBResultSet extends AbstractParentWrapper implements AutoCloseable // TODO: add concurrency control public static final Logger log = Logger.getLogger("DBResultSet"); - public static final int TYPE_DYNAMIC = ResultSet.TYPE_SCROLL_SENSITIVE + 1; - public static final int CONCUR_OPTIMISTIC = ResultSet.CONCUR_UPDATABLE + 2; - public static final int TYPE_CURSOR_FORWARDONLY = ResultSet.TYPE_FORWARD_ONLY + 1001; - public static final int TYPE_FORWARD_ONLY = ResultSet.TYPE_FORWARD_ONLY; - public static final int CONCUR_READ_ONLY = ResultSet.CONCUR_READ_ONLY; - public static final int TYPE_SCROLL_INSENSITIVE = ResultSet.TYPE_SCROLL_INSENSITIVE; - public static final int TYPE_SCROLL_SENSITIVE = ResultSet.TYPE_SCROLL_SENSITIVE; - public static final int CONCUR_UPDATABLE = ResultSet.CONCUR_UPDATABLE; - public static final int TYPE_DIRECT_FORWARDONLY = ResultSet.TYPE_FORWARD_ONLY + 1000; - protected DBTable currentTable; public int _currentrow = -1; // The row this rowset is currently pointing to @@ -184,7 +174,7 @@ public void verifyCurrentRow(DBTable table) throws SQLException { currentTable = table; int totalColumns = ((ResultSet) product()).getMetaData().getColumnCount(); - Class _class = Object.class; + Class _class = Object.class; for (int i = 0; i < totalColumns; i++) verifydata(i, _class); } @@ -196,7 +186,7 @@ public void verifyCurrentRow(DBTable table) throws SQLException { * @throws SQLException * @throws Exception */ - public void verifydata(int ordinal, Class coercion) throws SQLException { + public void verifydata(int ordinal, Class coercion) throws SQLException { Object expectedData = currentTable.columns.get(ordinal).getRowValue(_currentrow); // getXXX - default mapping @@ -219,7 +209,7 @@ public void verifydata(int ordinal, Class coercion) throws SQLException { * @param retrieved * @throws SQLException */ - public void verifydata(int ordinal, Class coercion, Object expectedData, Object retrieved) throws SQLException { + public void verifydata(int ordinal, Class coercion, Object expectedData, Object retrieved) throws SQLException { metaData = this.getMetaData(); switch (metaData.getColumnType(ordinal + 1)) { case java.sql.Types.BIGINT: @@ -350,7 +340,7 @@ public void verifydata(int ordinal, Class coercion, Object expectedData, Object * @return * @throws SQLException */ - public Object getXXX(Object idx, Class coercion) throws SQLException { + public Object getXXX(Object idx, Class coercion) throws SQLException { int intOrdinal = 0; String strOrdinal = ""; boolean isInteger = false; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSetTypes.java b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSetTypes.java index 0a76bfa50..bd7ad58f4 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSetTypes.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSetTypes.java @@ -11,13 +11,13 @@ public enum DBResultSetTypes { - TYPE_FORWARD_ONLY_CONCUR_READ_ONLY(DBResultSet.TYPE_FORWARD_ONLY, DBResultSet.CONCUR_READ_ONLY), - TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY(DBResultSet.TYPE_SCROLL_INSENSITIVE, DBResultSet.CONCUR_READ_ONLY), - TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY(DBResultSet.TYPE_SCROLL_SENSITIVE, DBResultSet.CONCUR_READ_ONLY), - TYPE_FORWARD_ONLY_CONCUR_UPDATABLE(DBResultSet.TYPE_FORWARD_ONLY, DBResultSet.CONCUR_UPDATABLE), - TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE(DBResultSet.TYPE_SCROLL_SENSITIVE, DBResultSet.CONCUR_UPDATABLE), - TYPE_DYNAMIC_CONCUR_OPTIMISTIC(DBResultSet.TYPE_DYNAMIC, DBResultSet.CONCUR_OPTIMISTIC), - TYPE_CURSOR_FORWARDONLY_CONCUR_UPDATABLE(DBResultSet.TYPE_CURSOR_FORWARDONLY, DBResultSet.CONCUR_READ_ONLY),; + TYPE_FORWARD_ONLY_CONCUR_READ_ONLY(DBConstants.RESULTSET_TYPE_FORWARD_ONLY, DBConstants.RESULTSET_CONCUR_READ_ONLY), + TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY(DBConstants.RESULTSET_TYPE_SCROLL_INSENSITIVE, DBConstants.RESULTSET_CONCUR_READ_ONLY), + TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY(DBConstants.RESULTSET_TYPE_SCROLL_SENSITIVE, DBConstants.RESULTSET_CONCUR_READ_ONLY), + TYPE_FORWARD_ONLY_CONCUR_UPDATABLE(DBConstants.RESULTSET_TYPE_FORWARD_ONLY, DBConstants.RESULTSET_CONCUR_UPDATABLE), + TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE(DBConstants.RESULTSET_TYPE_SCROLL_SENSITIVE, DBConstants.RESULTSET_CONCUR_UPDATABLE), + TYPE_DYNAMIC_CONCUR_OPTIMISTIC(DBConstants.RESULTSET_TYPE_DYNAMIC, DBConstants.RESULTSET_CONCUR_OPTIMISTIC), + TYPE_CURSOR_FORWARDONLY_CONCUR_UPDATABLE(DBConstants.RESULTSET_TYPE_CURSOR_FORWARDONLY, DBConstants.RESULTSET_CONCUR_READ_ONLY),; public int resultsetCursor; public int resultSetConcurrency; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java index 480877b36..ab68797da 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java @@ -23,13 +23,9 @@ public class DBStatement extends AbstractParentWrapper implements AutoCloseable // TODO: support PreparedStatement and CallableStatement // TODO: add stmt level holdability // TODO: support IDENTITY column and stmt.getGeneratedKeys() - public int cursortype = ResultSet.TYPE_FORWARD_ONLY; - public int concurrency = ResultSet.CONCUR_READ_ONLY; - public int holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT; - public static final int STATEMENT = 0; - public static final int PREPAREDSTATEMENT = 1; - public static final int CALLABLESTATEMENT = 2; - public static final int ALL = 3; + // public int cursortype = ResultSet.TYPE_FORWARD_ONLY; + // public int concurrency = ResultSet.CONCUR_READ_ONLY; + // public int holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT; Statement statement = null; DBResultSet dbresultSet = null; diff --git a/src/test/java/com/microsoft/sqlserver/testframework/PrepUtil.java b/src/test/java/com/microsoft/sqlserver/testframework/PrepUtil.java index 02971234b..ad1d2d8dd 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/PrepUtil.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/PrepUtil.java @@ -34,9 +34,7 @@ private PrepUtil() { * @throws SQLException * @throws ClassNotFoundException */ - public static SQLServerConnection getConnection(String connectionString, - Properties info) throws SQLException, ClassNotFoundException { - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); + public static SQLServerConnection getConnection(String connectionString, Properties info) throws SQLException { return (SQLServerConnection) DriverManager.getConnection(connectionString, info); } @@ -48,8 +46,7 @@ public static SQLServerConnection getConnection(String connectionString, * @throws SQLException * @throws ClassNotFoundException */ - public static SQLServerConnection getConnection( - String connectionString) throws SQLException, ClassNotFoundException { + public static SQLServerConnection getConnection(String connectionString) throws SQLException { return getConnection(connectionString, null); } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlBigInt.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlBigInt.java index 6219cb84b..8c82f7ae9 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlBigInt.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlBigInt.java @@ -19,7 +19,6 @@ public SqlBigInt() { } public Object createdata() { - // TODO: include max value return ThreadLocalRandom.current().nextLong(Long.MIN_VALUE, Long.MAX_VALUE); } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java index b412ca55a..e9eac3874 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlChar.java @@ -10,6 +10,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.DBCoercion; +import com.microsoft.sqlserver.testframework.DBConstants; /* @@ -28,15 +29,18 @@ public SqlChar() { super(name, jdbctype, precision, 0, SqlTypeValue.CHAR.minValue, SqlTypeValue.CHAR.maxValue, SqlTypeValue.CHAR.nullValue, VariableLengthType.Precision, String.class); generatePrecision(); - coercions.add(new DBCoercion(Object.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, - DBCoercion.UPDATEOBJECT, DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG})); - coercions - .add(new DBCoercion(String.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, - DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.CHAR})); + coercions.add(new DBCoercion(Object.class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION})); + coercions.add(new DBCoercion(String.class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION, DBConstants.CHAR_COERCION})); coercions.add(new DBCoercion(TestUtils.DBCharacterStream.class, - new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, DBCoercion.SET, - DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.STREAM, - DBCoercion.CHAR})); + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION, DBConstants.STREAM_COERCION, DBConstants.CHAR_COERCION})); } public Object createdata() { diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlNVarCharMax.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlNVarCharMax.java index f1eda908a..295e9d2e6 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlNVarCharMax.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlNVarCharMax.java @@ -9,6 +9,7 @@ import java.sql.NClob; import com.microsoft.sqlserver.testframework.DBCoercion; +import com.microsoft.sqlserver.testframework.DBConstants; public class SqlNVarCharMax extends SqlNVarChar { @@ -17,12 +18,16 @@ public SqlNVarCharMax() { super(); name = "nvarchar(max)"; jdbctype = JDBCType.LONGNVARCHAR; - variableLengthType = variableLengthType.Variable; - - coercions.add(new DBCoercion(Clob.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, - DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.CHAR})); - coercions.add(new DBCoercion(NClob.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, - DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.NCHAR})); + variableLengthType = VariableLengthType.Variable; + + coercions.add(new DBCoercion(Clob.class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION, DBConstants.CHAR_COERCION})); + coercions.add(new DBCoercion(NClob.class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION, DBConstants.NCHAR_COERCION})); } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlType.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlType.java index e8acf7c0b..edba5f703 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlType.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlType.java @@ -12,6 +12,7 @@ import com.microsoft.sqlserver.testframework.DBCoercion; import com.microsoft.sqlserver.testframework.DBCoercions; import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.DBConstants; import com.microsoft.sqlserver.testframework.DBItems; @@ -26,7 +27,7 @@ public abstract class SqlType extends DBItems { protected Object maxvalue = null; protected Object nullvalue = null; // Primitives have non-null defaults protected VariableLengthType variableLengthType; - protected Class type = null; + protected Class type = null; protected BitSet flags = new BitSet(); protected DBCoercions coercions = new DBCoercions(); @@ -236,16 +237,17 @@ public boolean isString() { * @return * @throws Exception */ - public boolean canConvert(Class target, int flag, DBConnection conn) throws Exception { + public boolean canConvert(Class target, int flag, DBConnection conn) throws Exception { double serverversion = conn.getServerVersion(); - if (flag == DBCoercion.SET || flag == DBCoercion.SETOBJECT || flag == DBCoercion.UPDATE - || flag == DBCoercion.UPDATEOBJECT || flag == DBCoercion.REG) { + if (flag == DBConstants.SET_COERCION || flag == DBConstants.SETOBJECT_COERCION + || flag == DBConstants.UPDATE_COERCION || flag == DBConstants.UPDATEOBJECT_COERCION + || flag == DBConstants.REG_COERCION) { // SQL 8 does not allow conversion from string to money - if (flag != DBCoercion.SETOBJECT && serverversion < 9.0 && this instanceof SqlMoney + if (flag != DBConstants.SETOBJECT_COERCION && serverversion < 9.0 && this instanceof SqlMoney && target == String.class) return false; - if (flag == DBCoercion.SET || flag == DBCoercion.SETOBJECT) { + if (flag == DBConstants.SET_COERCION || flag == DBConstants.SETOBJECT_COERCION) { // setTemporal() on textual columns returns unverifiable format if (this.isString() && (target == java.sql.Date.class || target == java.sql.Time.class || target == java.sql.Timestamp.class)) diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java index 3f9383e69..813810f6d 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinary.java @@ -10,6 +10,7 @@ import com.microsoft.sqlserver.jdbc.TestUtils.DBBinaryStream; import com.microsoft.sqlserver.jdbc.TestUtils.DBCharacterStream; import com.microsoft.sqlserver.testframework.DBCoercion; +import com.microsoft.sqlserver.testframework.DBConstants; /** @@ -22,22 +23,29 @@ public class SqlVarBinary extends SqlBinary { */ public SqlVarBinary() { super("varbinary", JDBCType.VARBINARY, 4000); - coercions.add(new DBCoercion(String.class, new int[] {DBCoercion.GET, DBCoercion.GETPARAM})); - coercions.add(new DBCoercion(Object.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, - DBCoercion.UPDATEOBJECT, DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG})); - coercions.add(new DBCoercion(byte[].class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, - DBCoercion.UPDATEOBJECT, DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG})); + coercions + .add(new DBCoercion(String.class, new int[] {DBConstants.GET_COERCION, DBConstants.GETPARAM_COERCION})); + coercions.add(new DBCoercion(Object.class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION})); + coercions.add(new DBCoercion(byte[].class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION})); // TODO: Following coercions are not supported by AE. add a check later // coercions.remove(String.class); - coercions.add(new DBCoercion(String.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, - DBCoercion.UPDATEOBJECT, DBCoercion.SETOBJECT, DBCoercion.GETPARAM})); + coercions.add(new DBCoercion(String.class, new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, + DBConstants.UPDATEOBJECT_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION})); coercions.add(new DBCoercion(DBBinaryStream.class, - new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, DBCoercion.SET, - DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.STREAM})); + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION, DBConstants.STREAM_COERCION})); coercions.add(new DBCoercion(DBCharacterStream.class, - new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, DBCoercion.SETOBJECT, - DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.STREAM})); + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, DBConstants.REG_COERCION, + DBConstants.STREAM_COERCION})); } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinaryMax.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinaryMax.java index ccc115211..b5b113558 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinaryMax.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarBinaryMax.java @@ -8,6 +8,7 @@ import java.sql.JDBCType; import com.microsoft.sqlserver.testframework.DBCoercion; +import com.microsoft.sqlserver.testframework.DBConstants; public class SqlVarBinaryMax extends SqlVarBinary { @@ -17,8 +18,10 @@ public SqlVarBinaryMax() { name = "varbinary(max)"; jdbctype = JDBCType.LONGVARBINARY; variableLengthType = variableLengthType.Variable; - coercions.add(new DBCoercion(Blob.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, - DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG})); + coercions.add(new DBCoercion(Blob.class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION})); } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarCharMax.java b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarCharMax.java index b8578cc33..87850dc32 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarCharMax.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/sqlType/SqlVarCharMax.java @@ -5,20 +5,22 @@ package com.microsoft.sqlserver.testframework.sqlType; import java.sql.Clob; +import java.sql.JDBCType; import com.microsoft.sqlserver.testframework.DBCoercion; +import com.microsoft.sqlserver.testframework.DBConstants; public class SqlVarCharMax extends SqlVarChar { public SqlVarCharMax() { - super(); name = "varchar(max)"; - jdbctype = jdbctype.LONGVARCHAR; - variableLengthType = variableLengthType.Variable; - coercions.add(new DBCoercion(Clob.class, new int[] {DBCoercion.GET, DBCoercion.UPDATE, DBCoercion.UPDATEOBJECT, - DBCoercion.SET, DBCoercion.SETOBJECT, DBCoercion.GETPARAM, DBCoercion.REG, DBCoercion.CHAR})); - + jdbctype = JDBCType.LONGVARCHAR; + variableLengthType = VariableLengthType.Variable; + coercions.add(new DBCoercion(Clob.class, + new int[] {DBConstants.GET_COERCION, DBConstants.UPDATE_COERCION, DBConstants.UPDATEOBJECT_COERCION, + DBConstants.SET_COERCION, DBConstants.SETOBJECT_COERCION, DBConstants.GETPARAM_COERCION, + DBConstants.REG_COERCION, DBConstants.CHAR_COERCION})); } }