diff --git a/.gitignore b/.gitignore index b8095970d9..17f1c1b0a9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,238 +1,239 @@ -################# -## Eclipse -################# - -.project -.metadata -bin/ -tmp/ -target/ -build/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.classpath -.vscode/ -.settings/ -.gradle/ -.loadpath -outdated-dependencies.txt -pom.xml.versionBackup - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath - - -################# -## Visual Studio -################# - -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.sln.docstates - -# Build results - -[Dd]ebug/ -[Rr]elease/ -x64/ -build/ -[Bb]in/ -[Oo]bj/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -*_i.c -*_p.c -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.log -*.scc - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf -*.cachefile - -# Visual Studio profiler -*.psess -*.vsp -*.vspx - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -*.ncrunch* -.*crunch*.local.xml - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.Publish.xml -*.pubxml -*.publishproj - -# NuGet Packages Directory -## TODO: If you have NuGet Package Restore enabled, uncomment the next line -#packages/ - -# Windows Azure Build Output -csx -*.build.csdef - -# Windows Store app package directory -AppPackages/ - -# Others -sql/ -*.Cache -ClientBin/ -[Ss]tyle[Cc]op.* -~$* -*~ -*.dbmdl -*.[Pp]ublish.xml -*.pfx -*.publishsettings - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file to a newer -# Visual Studio version. Backup files are not needed, because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -App_Data/*.mdf -App_Data/*.ldf - -############# -## Windows detritus -############# - -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Mac crap -.DS_Store - - -############# -## Python -############# - -*.py[cod] - -# Packages -*.egg -*.egg-info -dist/ -build/ -eggs/ -parts/ -var/ -sdist/ -develop-eggs/ -.installed.cfg - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox - -#Translations -*.mo - -#Mr Developer -.mr.developer.cfg - - -############# -## Intellij -############# - -## Directory-based project format -.idea/ - -## File-based project format -*.ipr -*.iws -*.iml - -## Additional for IntelliJ -out/ -gen/ \ No newline at end of file +################# +## Eclipse +################# + +.project +.metadata +bin/ +tmp/ +target/ +build/ +AE_Certificates/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.vscode/ +.settings/ +.gradle/ +.loadpath +outdated-dependencies.txt +pom.xml.versionBackup + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml +*.pubxml +*.publishproj + +# NuGet Packages Directory +## TODO: If you have NuGet Package Restore enabled, uncomment the next line +#packages/ + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +App_Data/*.mdf +App_Data/*.ldf + +############# +## Windows detritus +############# + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Mac crap +.DS_Store + + +############# +## Python +############# + +*.py[cod] + +# Packages +*.egg +*.egg-info +dist/ +build/ +eggs/ +parts/ +var/ +sdist/ +develop-eggs/ +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg + + +############# +## Intellij +############# + +## Directory-based project format +.idea/ + +## File-based project format +*.ipr +*.iws +*.iml + +## Additional for IntelliJ +out/ +gen/ diff --git a/.travis.yml b/.travis.yml index 1a4299131d..af46163422 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,7 @@ language: java jdk: - - oraclejdk10 + - oraclejdk11 services: - docker diff --git a/CHANGELOG.md b/CHANGELOG.md index b01ab74e4d..4e736de77b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,11 +3,34 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## [7.1.2] Preview Release +### Added +- Added support for JDK 11 [#824](https://github.com/Microsoft/mssql-jdbc/pull/824) [#837](https://github.com/Microsoft/mssql-jdbc/pull/837) [#807](https://github.com/Microsoft/mssql-jdbc/pull/807) +- Updated SQL keywords in DatabaseMetaData [#829](https://github.com/Microsoft/mssql-jdbc/pull/829) +- Improvements in DatabaseMetadata to prevent Statement leaks and enhance Statement caching [#806](https://github.com/Microsoft/mssql-jdbc/pull/806) + +### Fixed Issues +- Fixed slf4j warning message in tests [#841](https://github.com/Microsoft/mssql-jdbc/pull/841) +- Fixed potential NullPointerException in logException() [#844](https://github.com/Microsoft/mssql-jdbc/pull/844) +- Fixed intermittent failures in JUnit - LobsTest [#827](https://github.com/Microsoft/mssql-jdbc/pull/827) +- Fixed useBulkCopyForBatchInserts API to respect Statement timeout value [#817](https://github.com/Microsoft/mssql-jdbc/pull/817) + +### Changed +- Updated JUnit tests to remove hard-coded names [#809](https://github.com/Microsoft/mssql-jdbc/pull/809) +- Removed illegal reflection access in Kerberos Authentication [#839](https://github.com/Microsoft/mssql-jdbc/pull/839) +- Enabled non-running JUnit tests [#847](https://github.com/Microsoft/mssql-jdbc/pull/847) +- Updated Clobs to use StandardCharsets.US_ASCII instead of hard-coded string [#855](https://github.com/Microsoft/mssql-jdbc/pull/855) +- Code cleanup [#821](https://github.com/Microsoft/mssql-jdbc/pull/821) [#825](https://github.com/Microsoft/mssql-jdbc/pull/825) + ## [7.1.1] Preview Release +### Added +- Added streaming capabilities for Clob.getAsciiStream() [#799](https://github.com/Microsoft/mssql-jdbc/pull/799) + ### Fixed Issues - Fixed a bug where calling length() after obtaining a stream would close the stream for Clobs/NClobs [#799](https://github.com/Microsoft/mssql-jdbc/pull/799) +- Fixed Clob/NClob encoding issues [#799](https://github.com/Microsoft/mssql-jdbc/pull/799) - Fixed issues in Bulk Copy exception handling [#801](https://github.com/Microsoft/mssql-jdbc/pull/801) -- Fixed closeable resource leaks in Junit tests [#797](https://github.com/Microsoft/mssql-jdbc/pull/797) +- Fixed closeable resource leaks in JUnit tests [#797](https://github.com/Microsoft/mssql-jdbc/pull/797) - Fixed issues with apostrophe being passed in table name [#780](https://github.com/Microsoft/mssql-jdbc/pull/780) - Fixed statement leaks and improved exception handling in SQLServerParameterMetadata [#780](https://github.com/Microsoft/mssql-jdbc/pull/780) @@ -67,7 +90,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) ### Added - Added removed constructor back to AKV Provider which supports authentication with a customized method to fetch accessToken [#675](https://github.com/Microsoft/mssql-jdbc/pull/675) - Added support for JDK 10 for both Maven and Gradle [#691](https://github.com/Microsoft/mssql-jdbc/pull/691) -- Added a resource bundle to handle junit error strings [#698](https://github.com/Microsoft/mssql-jdbc/pull/698) +- Added a resource bundle to handle JUnit error strings [#698](https://github.com/Microsoft/mssql-jdbc/pull/698) ### Fixed Issues - Fixed the driver disposing user created credentials when using Kerberos Constrained Delegation [#636](https://github.com/Microsoft/mssql-jdbc/pull/636) @@ -202,7 +225,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) ## [6.3.1] Preview Release ### Added - Added support for datetime/smallDatetime in TVP [#435](https://github.com/Microsoft/mssql-jdbc/pull/435) -- Added more Junit tests for Always Encrypted [#432](https://github.com/Microsoft/mssql-jdbc/pull/432) +- Added more JUnit tests for Always Encrypted [#432](https://github.com/Microsoft/mssql-jdbc/pull/432) ### Fixed Issues - Fixed getString issue for uniqueIdentifier [#423](https://github.com/Microsoft/mssql-jdbc/pull/423) @@ -214,7 +237,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) ## [6.3.0] Preview Release ### Added - Added support for sql_variant datatype [#387](https://github.com/Microsoft/mssql-jdbc/pull/387) -- Added more Junit tests for Always Encrypted [#404](https://github.com/Microsoft/mssql-jdbc/pull/404) +- Added more JUnit tests for Always Encrypted [#404](https://github.com/Microsoft/mssql-jdbc/pull/404) ### Fixed Issues - Fixed Turkey locale issue when lowercasing an "i" [#384](https://github.com/Microsoft/mssql-jdbc/pull/384) @@ -318,7 +341,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) ### Added - Added socket timeout exception as cause[#180](https://github.com/Microsoft/mssql-jdbc/pull/180) - Added Constrained delegation support[#178](https://github.com/Microsoft/mssql-jdbc/pull/178) -- Added junit test for Statement test[#174](https://github.com/Microsoft/mssql-jdbc/pull/174) +- Added JUnit test for Statement test[#174](https://github.com/Microsoft/mssql-jdbc/pull/174) - Added test for statement.cancel() when MultiSubnetFailover is set to true[#173](https://github.com/Microsoft/mssql-jdbc/pull/173) - Added tests for lobs [#168](https://github.com/Microsoft/mssql-jdbc/pull/168) - Added badges for License, Maven Central, JavaDocs & gitter chat room [#184](https://github.com/Microsoft/mssql-jdbc/pull/184) @@ -360,7 +383,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) ### Changed - Switched to clean rounding for bigDecimal [#118](https://github.com/Microsoft/mssql-jdbc/pull/118) - Updated BVT tests to use jUnit test framework [#120](https://github.com/Microsoft/mssql-jdbc/pull/120) - - In case of socket timeout occurance, avoid connection retry [#122](https://github.com/Microsoft/mssql-jdbc/pull/122) + - In case of socket timeout occurrence, avoid connection retry [#122](https://github.com/Microsoft/mssql-jdbc/pull/122) - Changed ant build file to skip tests [#126](https://github.com/Microsoft/mssql-jdbc/pull/126) ### Fixed Issues diff --git a/README.md b/README.md index 375137e46d..51c931dd59 100644 --- a/README.md +++ b/README.md @@ -36,26 +36,26 @@ What's coming next? We will look into adding a more comprehensive set of tests, ## Build ### Prerequisites -* Java 10 +* Java 11 * [Maven](http://maven.apache.org/download.cgi) * An instance of SQL Server or Azure SQL Database that you can connect to. ### Build the JAR files Maven builds automatically trigger a set of verification tests to run. For these tests to pass, you will first need to add an environment variable in your system called `mssql_jdbc_test_connection_properties` to provide the [correct connection properties](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url) for your SQL Server or Azure SQL Database instance. -To build the jar files, you must use Java 10 with Maven. You can choose to build a JDBC 4.3 compliant jar file (for use with JRE 10) and/or a JDBC 4.2 compliant jar file (for use with JRE 8). +To build the jar files, you must use Java 11 with Maven. You can choose to build a JDBC 4.3 compliant jar file (for use with JRE 11) and/or a JDBC 4.2 compliant jar file (for use with JRE 8). * Maven: 1. If you have not already done so, add the environment variable `mssql_jdbc_test_connection_properties` in your system with the connection properties for your SQL Server or SQL DB instance. - 2. Run one of the commands below to build a JDBC 4.3 compliant jar or JDBC 4.2 compliant jar in the \target directory. - * Run `mvn install -Pbuild43`. This creates JDBC 4.3 compliant jar in \target directory - * Run `mvn install -Pbuild42`. This creates JDBC 4.2 compliant jar in \target directory + 2. Run one of the commands below to build a JDBC 4.3 compliant jar or JDBC 4.2 compliant jar in the `\target` directory. + * Run `mvn install -Pbuild43`. This creates JDBC 4.3 compliant jar in `\target` directory + * Run `mvn install -Pbuild42`. This creates JDBC 4.2 compliant jar in `\target` directory * Gradle: 1. If you have not already done so, add the environment variable `mssql_jdbc_test_connection_properties` in your system with the connection properties for your SQL Server or SQL DB instance. - 2. Run one of the commands below to build a JDBC 4.3 compliant jar or JDBC 4.2 compliant jar in the \build\libs directory. - * Run `gradle build -PbuildProfile=build43`. This creates JDBC 4.3 compliant jar in \build\libs directory - * Run `gradle build -PbuildProfile=build42`. This creates JDBC 4.2 compliant jar in \build\libs directory + 2. Run one of the commands below to build a JDBC 4.3 compliant jar or JDBC 4.2 compliant jar in the `\build\libs` directory. + * Run `gradle build -PbuildProfile=build43`. This creates JDBC 4.3 compliant jar in `\build\libs` directory + * Run `gradle build -PbuildProfile=build42`. This creates JDBC 4.2 compliant jar in `\build\libs` directory ## Resources @@ -65,7 +65,7 @@ API reference documentation is available in [Javadocs](https://aka.ms/jdbcjavado This driver is documented on [Microsoft's Documentation web site](https://docs.microsoft.com/en-us/sql/connect/jdbc/getting-started-with-the-jdbc-driver). ### Sample Code -For samples, please see the src\sample directory. +For samples, please see the `src\sample` directory. ### Download the DLLs For some features (e.g. Integrated Authentication and Distributed Transactions), you may need to use the `sqljdbc_xa` and `sqljdbc_auth` DLLs. They can be downloaded from the [Microsoft Download Center](https://go.microsoft.com/fwlink/?linkid=868287) @@ -90,7 +90,7 @@ To get the latest preview version of the driver, add the following to your POM f com.microsoft.sqlserver mssql-jdbc - 7.1.1.jre10-preview + 7.1.2.jre11-preview ``` @@ -123,7 +123,7 @@ Projects that require either of the two features need to explicitly declare the com.microsoft.sqlserver mssql-jdbc - 7.1.1.jre10-preview + 7.1.2.jre11-preview compile @@ -140,7 +140,7 @@ Projects that require either of the two features need to explicitly declare the com.microsoft.sqlserver mssql-jdbc - 7.1.1.jre10-preview + 7.1.2.jre11-preview compile diff --git a/appveyor.yml b/appveyor.yml index 6ab08769cd..3e70b718ba 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -27,13 +27,13 @@ install: cache: - C:\Users\appveyor\.m2 -> pom.xml +# Disable build and test scripts till Java 11 is supported build_script: - - keytool -importkeystore -srckeystore cert.pfx -srcstoretype pkcs12 -destkeystore clientcert.jks -deststoretype JKS -srcstorepass password -deststorepass password - - keytool -list -v -keystore clientcert.jks -storepass "password" > JavaKeyStore.txt - - cd.. - - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -Pbuild43 - - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -Pbuild42 - -test_script: - - mvn test -B -Pbuild43 - - mvn test -B -Pbuild42 + - keytool -importkeystore -srckeystore cert.pfx -srcstoretype pkcs12 -destkeystore clientcert.jks -deststoretype JKS -srcstorepass password -deststorepass password + - keytool -list -v -keystore clientcert.jks -storepass "password" > JavaKeyStore.txt +# - cd.. +# - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -Pbuild43 +# - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -Pbuild42 +# test_script: +# - mvn test -B -Pbuild43 +# - mvn test -B -Pbuild42 diff --git a/build.gradle b/build.gradle index 34c86772c9..0688b4aedf 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ apply plugin: 'java' -version = '7.1.1' +version = '7.1.2' def jreVersion = "" def testOutputDir = file("build/classes/java/test") def archivesBaseName = 'mssql-jdbc' @@ -27,15 +27,15 @@ allprojects { if (!hasProperty('buildProfile') || (hasProperty('buildProfile') && buildProfile == "build43")){ - jreVersion = "jre10-preview" + jreVersion = "jre11-preview" excludedFile = 'com/microsoft/sqlserver/jdbc/SQLServerJdbc42.java' jar { manifest { attributes 'Automatic-Module-Name': 'com.microsoft.sqlserver.jdbc' } } - sourceCompatibility = 10 - targetCompatibility = 10 + sourceCompatibility = 11 + targetCompatibility = 11 } if((hasProperty('buildProfile') && buildProfile == "build42")) { @@ -82,16 +82,19 @@ repositories { } dependencies { - compileOnly 'com.microsoft.azure:azure-keyvault:1.0.0', - 'com.microsoft.azure:adal4j:1.6.0' - testCompile 'org.junit.platform:junit-platform-console:1.2.0', - 'org.junit.platform:junit-platform-commons:1.2.0', - 'org.junit.platform:junit-platform-engine:1.2.0', - 'org.junit.platform:junit-platform-launcher:1.2.0', - 'org.junit.platform:junit-platform-runner:1.2.0', - 'org.junit.platform:junit-platform-surefire-provider:1.2.0', - 'org.junit.jupiter:junit-jupiter-api:5.2.0', - 'org.junit.jupiter:junit-jupiter-engine:5.2.0', + compileOnly 'com.microsoft.azure:azure-keyvault:1.1.1', + 'com.microsoft.azure:azure-keyvault-webkey:1.1.1', + 'com.microsoft.rest:client-runtime:1.6.2', + 'com.microsoft.azure:adal4j:1.6.2' + testCompile 'org.junit.platform:junit-platform-console:1.3.1', + 'org.junit.platform:junit-platform-commons:1.3.1', + 'org.junit.platform:junit-platform-engine:1.3.1', + 'org.junit.platform:junit-platform-launcher:1.3.1', + 'org.junit.platform:junit-platform-runner:1.3.1', + 'org.junit.platform:junit-platform-surefire-provider:1.3.1', + 'org.junit.jupiter:junit-jupiter-api:5.3.1', + 'org.junit.jupiter:junit-jupiter-engine:5.3.1', 'com.zaxxer:HikariCP:3.2.0', - 'org.apache.commons:commons-dbcp2:5.0' + 'org.apache.commons:commons-dbcp2:2.5.0', + 'org.slf4j:slf4j-nop:1.7.25' } diff --git a/pom.xml b/pom.xml index f6de796709..9505b50557 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.microsoft.sqlserver mssql-jdbc - 7.1.1 + 7.1.2 jar Microsoft JDBC Driver for SQL Server @@ -39,22 +39,33 @@ UTF-8 - 1.2.0 - 5.2.0 + 1.3.1 + 5.3.1 com.microsoft.azure azure-keyvault - 1.0.0 + 1.1.1 + true + + + com.microsoft.azure + azure-keyvault-webkey + 1.1.1 true - com.microsoft.azure adal4j - 1.6.0 + 1.6.2 + true + + + com.microsoft.rest + client-runtime + 1.6.2 true @@ -119,6 +130,12 @@ 2.5.0 test + + org.slf4j + slf4j-nop + 1.7.25 + test + @@ -128,8 +145,9 @@ ${project.artifactId}-${project.version}.jre8-preview + org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + 3.8.0 **/com/microsoft/sqlserver/jdbc/SQLServerJdbc43.java @@ -148,27 +166,60 @@ + + org.jacoco + jacoco-maven-plugin + 0.8.2 + + + pre-test + + prepare-agent + + + + report + test + + report + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + + ${argLine} --illegal-access=permit + + + ${skipTestTag} + + + - build43 true - ${project.artifactId}-${project.version}.jre10-preview + ${project.artifactId}-${project.version}.jre11-preview + org.apache.maven.plugins maven-compiler-plugin - 3.7.0 + 3.8.0 **/com/microsoft/sqlserver/jdbc/SQLServerJdbc42.java - 10 - 10 + 11 + 11 @@ -184,14 +235,44 @@ + + org.jacoco + jacoco-maven-plugin + 0.8.2 + + + pre-test + + prepare-agent + + + + report + test + + report + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.0 + + + ${argLine} --illegal-access=permit + + + ${skipTestTag} + + + - - - ${basedir} @@ -200,7 +281,6 @@ - src/test/resources @@ -216,39 +296,48 @@ - - org.apache.maven.plugins - maven-source-plugin - 3.0.1 + maven-enforcer-plugin + 3.0.0-M2 - attach-sources + enforce-versions - jar + enforce + + + + + WARN + + org.apache.maven.plugins:maven-verifier-plugin + + Please consider using the maven-invoker-plugin + (http://maven.apache.org/plugins/maven-invoker-plugin/)! + + + 3.0.5 + + + 11 + + + - - org.jacoco - jacoco-maven-plugin - 0.8.1 + org.apache.maven.plugins + maven-source-plugin + 3.0.1 - pre-test - - prepare-agent - - - - report - test + attach-sources - report + jar @@ -261,7 +350,10 @@ true - com.microsoft.sqlserver.jdbc,microsoft.sql + <_exportcontents>export com.microsoft.sqlserver.jdbc + <_exportcontents>export microsoft.sql + <_exportcontents>export + com.microsoft.sqlserver.jdbc.dataclassification !microsoft.sql,* @@ -275,16 +367,13 @@ - org.apache.maven.plugins maven-javadoc-plugin 3.0.0 - true - attach-javadocs @@ -294,27 +383,6 @@ - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.0 - - - - ${skipTestTag} - - - - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - - - org.codehaus.mojo versions-maven-plugin @@ -325,8 +393,6 @@ file:///${session.executionRootDirectory}/maven-version-rules.xml - - diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java index 1fa3e55dad..845fe5b900 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java @@ -1129,7 +1129,7 @@ static String convertReaderToString(Reader reader, int readerLength) throws SQLS try { // Set up a StringBuilder big enough to hold the Reader value. If we weren't told the size of // the value then start with a "reasonable" guess StringBuilder size. If necessary, the StringBuilder - // will grow automatically to accomodate arbitrary amounts of data. + // will grow automatically to accommodate arbitrary amounts of data. StringBuilder sb = new StringBuilder( (DataTypes.UNKNOWN_STREAM_LENGTH != readerLength) ? readerLength : 4000); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DLLException.java b/src/main/java/com/microsoft/sqlserver/jdbc/DLLException.java index 1f78a96978..a46ad5b231 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DLLException.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DLLException.java @@ -10,7 +10,7 @@ /** * - * This class is used to handle exceptions that may be recieved from sqljdbc_auth.dll and sqljdbc_xa.dll + * This class is used to handle exceptions that may be received from sqljdbc_auth.dll and sqljdbc_xa.dll * */ class DLLException extends Exception { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index cce14b03e7..0cabb29360 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -2484,7 +2484,7 @@ private void findSocketUsingJavaNIO(InetAddress[] inetAddrs, int portNumber, } catch (IOException ex) { if (logger.isLoggable(Level.FINER)) logger.finer(this.toString() + " the exception: " + ex.getClass() + " with message: " - + ex.getMessage() + " occured while processing the channel: " + ch); + + ex.getMessage() + " occurred while processing the channel: " + ch); updateSelectedException(ex, this.toString()); // close the channel pro-actively so that we do not // rely to network resources @@ -2913,7 +2913,7 @@ public void run() { } catch (IOException ex) { if (logger.isLoggable(Level.FINER)) { logger.finer(this.toString() + " exception:" + ex.getClass() + " with message:" + ex.getMessage() - + " occured while connecting to InetSocketAddress:" + inetSocketAddress); + + " occurred while connecting to InetSocketAddress:" + inetSocketAddress); } exception = ex; } @@ -3281,7 +3281,7 @@ void writeBigDecimal(BigDecimal bigDecimalVal, int srcJdbcType, int precision, */ /* - * setScale of all BigDecimal value based on metadata as scale is not sent seperately for individual value. Use + * setScale of all BigDecimal value based on metadata as scale is not sent separately for individual value. Use * the rounding used in Server. Say, for BigDecimal("0.1"), if scale in metdadata is 0, then ArithmeticException * would be thrown if RoundingMode is not set */ @@ -4099,7 +4099,7 @@ void flush(boolean atEOM) throws SQLServerException { * @param sName * the optional parameter name * @param bOut - * boolean true if the value that follows is being registered as an ouput parameter + * boolean true if the value that follows is being registered as an output parameter * @param tdsType * TDS type of the value that follows */ @@ -4130,7 +4130,7 @@ void writeRPCNameValType(String sName, boolean bOut, TDSType tdsType) throws SQL * @param booleanValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCBit(String sName, Boolean booleanValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.BITN); @@ -4151,7 +4151,7 @@ void writeRPCBit(String sName, Boolean booleanValue, boolean bOut) throws SQLSer * @param shortValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCByte(String sName, Byte byteValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); @@ -4172,7 +4172,7 @@ void writeRPCByte(String sName, Byte byteValue, boolean bOut) throws SQLServerEx * @param shortValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCShort(String sName, Short shortValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); @@ -4193,7 +4193,7 @@ void writeRPCShort(String sName, Short shortValue, boolean bOut) throws SQLServe * @param intValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCInt(String sName, Integer intValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); @@ -4214,7 +4214,7 @@ void writeRPCInt(String sName, Integer intValue, boolean bOut) throws SQLServerE * @param longValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCLong(String sName, Long longValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.INTN); @@ -4235,7 +4235,7 @@ void writeRPCLong(String sName, Long longValue, boolean bOut) throws SQLServerEx * @param floatValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCReal(String sName, Float floatValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.FLOATN); @@ -4269,7 +4269,7 @@ void writeRPCSqlVariant(String sName, SqlVariant sqlVariantValue, boolean bOut) * @param doubleValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCDouble(String sName, Double doubleValue, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.FLOATN); @@ -4303,7 +4303,7 @@ void writeRPCDouble(String sName, Double doubleValue, boolean bOut) throws SQLSe * @param nScale * the desired scale * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter */ void writeRPCBigDecimal(String sName, BigDecimal bdValue, int nScale, boolean bOut) throws SQLServerException { writeRPCNameValType(sName, bOut, TDSType.DECIMALN); @@ -4364,7 +4364,7 @@ void writeRPCStringUnicode(String sValue) throws SQLServerException { * @param sValue * the data value * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter * @param collation * the collation of the data value */ @@ -4679,7 +4679,7 @@ private void writeInternalTVPRowValues(JDBCType jdbcType, String currentColumnSt BigDecimal bdValue = new BigDecimal(currentColumnStringValue); /* - * setScale of all BigDecimal value based on metadata as scale is not sent seperately for individual + * setScale of all BigDecimal value based on metadata as scale is not sent separately for individual * value. Use the rounding used in Server. Say, for BigDecimal("0.1"), if scale in metdadata is 0, * then ArithmeticException would be thrown if RoundingMode is not set */ @@ -5239,7 +5239,7 @@ void writeRPCByteArray(String sName, byte bValue[], boolean bOut, JDBCType jdbcT * @param subSecondNanos * the sub-second nanoseconds (0 - 999,999,999) * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter * */ void writeRPCDateTime(String sName, GregorianCalendar cal, int subSecondNanos, @@ -5934,7 +5934,7 @@ private byte[] scaledNanosToEncodedBytes(long scaledNanos, int encodedLength) { * @param streamLength * length of the stream (may be unknown) * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter * @param jdbcType * The JDBC type used to determine whether the value is textual or non-textual. * @param collation @@ -6033,7 +6033,7 @@ void writeRPCInputStream(String sName, InputStream stream, long streamLength, bo * @param streamLength * length of the stream (may be unknown) * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter * @throws SQLServerException */ void writeRPCXML(String sName, InputStream stream, long streamLength, boolean bOut) throws SQLServerException { @@ -6072,7 +6072,7 @@ void writeRPCXML(String sName, InputStream stream, long streamLength, boolean bO * @param reLength * the reader data length (in characters) * @param bOut - * boolean true if the data value is being registered as an ouput parameter + * boolean true if the data value is being registered as an output parameter * @param collation * The SQL collation associated with the value. Null for non-textual SQL Server types. * @throws SQLServerException diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/KerbAuthentication.java b/src/main/java/com/microsoft/sqlserver/jdbc/KerbAuthentication.java index 47c95e9de7..d0a99ba1c6 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/KerbAuthentication.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/KerbAuthentication.java @@ -251,7 +251,7 @@ private String enrichSpnWithRealm(String spn, boolean allowHostnameCanonicalizat } String dnsName = m.group(1); String portOrInstance = m.group(2); - RealmValidator realmValidator = getRealmValidator(dnsName); + RealmValidator realmValidator = getRealmValidator(); String realm = findRealmFromHostname(realmValidator, dnsName); if (realm == null && allowHostnameCanonicalization) { // We failed, try with canonical host name to find a better match @@ -277,50 +277,15 @@ private String enrichSpnWithRealm(String spn, boolean allowHostnameCanonicalizat private static RealmValidator validator; /** - * Find a suitable way of validating a REALM for given JVM. + * Get validator to validate REALM for given JVM. * - * @param hostnameToTest - * an example hostname we are gonna use to test our realm validator. - * @return a not null realm Validator. + * @return a not null realm validator. */ - static RealmValidator getRealmValidator(String hostnameToTest) { + static RealmValidator getRealmValidator() { if (validator != null) { return validator; } - // JVM Specific, here Sun/Oracle JVM - try { - Class clz = Class.forName("sun.security.krb5.Config"); - Method getInstance = clz.getMethod("getInstance", new Class[0]); - final Method getKDCList = clz.getMethod("getKDCList", new Class[] {String.class}); - final Object instance = getInstance.invoke(null); - RealmValidator oracleRealmValidator = new RealmValidator() { - - @Override - public boolean isRealmValid(String realm) { - try { - Object ret = getKDCList.invoke(instance, realm); - return ret != null; - } catch (Exception err) { - return false; - } - } - }; - validator = oracleRealmValidator; - // As explained here: https://github.com/Microsoft/mssql-jdbc/pull/40#issuecomment-281509304 - // The default Oracle Resolution mechanism is not bulletproof - // If it resolves a non-existing name, drop it. - if (!validator.isRealmValid("this.might.not.exist." + hostnameToTest)) { - // Our realm validator is well working, return it - authLogger.fine("Kerberos Realm Validator: Using Built-in Oracle Realm Validation method."); - return oracleRealmValidator; - } - authLogger - .fine("Kerberos Realm Validator: Detected buggy Oracle Realm Validator, using DNSKerberosLocator."); - } catch (ReflectiveOperationException notTheRightJVMException) { - // Ignored, we simply are not using the right JVM - authLogger.fine("Kerberos Realm Validator: No Oracle Realm Validator Available, using DNSKerberosLocator."); - } - // No implementation found, default one, not any realm is valid + validator = new RealmValidator() { @Override public boolean isRealmValid(String realm) { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java b/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java index 1da236fcb1..32e02dc578 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/KeyStoreProviderCommon.java @@ -142,19 +142,19 @@ private static byte[] decryptRSAOAEP(byte[] cipherText, private static boolean verifyRSASignature(byte[] hash, byte[] signature, X509Certificate certificate, String masterKeyPath) throws SQLServerException { Signature signVerify; - boolean verificationSucess = false; + boolean verificationSuccess = false; try { signVerify = Signature.getInstance("SHA256withRSA"); signVerify.initVerify(certificate.getPublicKey()); signVerify.update(hash); - verificationSucess = signVerify.verify(signature); + verificationSuccess = signVerify.verify(signature); } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_InvalidCertificateSignature")); Object[] msgArgs = {masterKeyPath}; throw new SQLServerException(form.format(msgArgs), e); } - return verificationSucess; + return verificationSuccess; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/Parameter.java b/src/main/java/com/microsoft/sqlserver/jdbc/Parameter.java index 93758a09cb..6e8e0a2daa 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/Parameter.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/Parameter.java @@ -34,7 +34,7 @@ final class Parameter { // Value type info for OUT parameters (excluding return status) private TypeInfo typeInfo; - // For unencrypted paramters cryptometa will be null. For encrypted parameters it will hold encryption metadata. + // For unencrypted parameters cryptometa will be null. For encrypted parameters it will hold encryption metadata. CryptoMetadata cryptoMeta = null; TypeInfo getTypeInfo() { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java index 3aa3f97915..de354b40e4 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java @@ -8,6 +8,6 @@ final class SQLJdbcVersion { static final int major = 7; static final int minor = 1; - static final int patch = 1; + static final int patch = 2; static final int build = 0; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java index 5968eba254..068e400117 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java @@ -1700,9 +1700,11 @@ private void getDestinationMetadata() throws SQLServerException { SQLServerException.getErrString("R_invalidDestinationTable"), null, false); } + String escapedDestinationTableName = Util.escapeSingleQuotes(destinationTableName); + SQLServerResultSet rs = null; - SQLServerResultSet rsMoreMetaData = null; SQLServerStatement stmt = null; + String metaDataQuery = null; try { if (null != destinationTableMetadata) { @@ -1713,7 +1715,7 @@ private void getDestinationMetadata() throws SQLServerException { // Get destination metadata rs = stmt.executeQueryInternal("sp_executesql N'SET FMTONLY ON SELECT * FROM " - + Util.escapeSingleQuotes(destinationTableName) + " '"); + + escapedDestinationTableName + " '"); } destColumnCount = rs.getMetaData().getColumnCount(); @@ -1721,27 +1723,26 @@ private void getDestinationMetadata() throws SQLServerException { destCekTable = rs.getCekTable(); if (!connection.getServerSupportsColumnEncryption()) { - // SQL server prior to 2016 does not support encryption_type - rsMoreMetaData = ((SQLServerStatement) connection.createStatement()) - .executeQueryInternal("select collation_name from sys.columns where " + "object_id=OBJECT_ID('" - + Util.escapeSingleQuotes(destinationTableName) + "') " + "order by column_id ASC"); + metaDataQuery = "select collation_name from sys.columns where " + "object_id=OBJECT_ID('" + + escapedDestinationTableName + "') " + "order by column_id ASC"; } else { - rsMoreMetaData = ((SQLServerStatement) connection.createStatement()).executeQueryInternal( - "select collation_name, encryption_type from sys.columns where " + "object_id=OBJECT_ID('" - + Util.escapeSingleQuotes(destinationTableName) + "') " + "order by column_id ASC"); + metaDataQuery = "select collation_name, encryption_type from sys.columns where " + + "object_id=OBJECT_ID('" + escapedDestinationTableName + "') " + "order by column_id ASC"; } - for (int i = 1; i <= destColumnCount; ++i) { - if (rsMoreMetaData.next()) { - if (!connection.getServerSupportsColumnEncryption()) { + + try (SQLServerStatement statementMoreMetadata = (SQLServerStatement) connection.createStatement(); + SQLServerResultSet rsMoreMetaData = statementMoreMetadata.executeQueryInternal(metaDataQuery)) { + for (int i = 1; i <= destColumnCount; ++i) { + if (rsMoreMetaData.next()) { + String bulkCopyEncryptionType = null; + if (connection.getServerSupportsColumnEncryption()) { + bulkCopyEncryptionType = rsMoreMetaData.getString("encryption_type"); + } destColumnMetadata.put(i, new BulkColumnMetaData(rs.getColumn(i), - rsMoreMetaData.getString("collation_name"), null)); + rsMoreMetaData.getString("collation_name"), bulkCopyEncryptionType)); } else { - destColumnMetadata.put(i, - new BulkColumnMetaData(rs.getColumn(i), rsMoreMetaData.getString("collation_name"), - rsMoreMetaData.getString("encryption_type"))); + destColumnMetadata.put(i, new BulkColumnMetaData(rs.getColumn(i))); } - } else { - destColumnMetadata.put(i, new BulkColumnMetaData(rs.getColumn(i))); } } } catch (SQLException e) { @@ -1752,8 +1753,6 @@ private void getDestinationMetadata() throws SQLServerException { rs.close(); if (null != stmt) stmt.close(); - if (null != rsMoreMetaData) - rsMoreMetaData.close(); } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java index 87054ef958..6331df080a 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java @@ -2265,51 +2265,51 @@ public void registerOutParameter(String parameterName, int sqlType) throws SQLSe } @Override - public void registerOutParameter(int paramterIndex, SQLType sqlType) throws SQLServerException { + public void registerOutParameter(int parameterIndex, SQLType sqlType) throws SQLServerException { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "registerOutParameter", - new Object[] {paramterIndex, sqlType}); + new Object[] {parameterIndex, sqlType}); // getVendorTypeNumber() returns the same constant integer values as in java.sql.Types - registerOutParameter(paramterIndex, sqlType.getVendorTypeNumber()); + registerOutParameter(parameterIndex, sqlType.getVendorTypeNumber()); loggerExternal.exiting(getClassNameLogging(), "registerOutParameter"); } @Override - public void registerOutParameter(int paramterIndex, SQLType sqlType, String typeName) throws SQLServerException { + public void registerOutParameter(int parameterIndex, SQLType sqlType, String typeName) throws SQLServerException { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "registerOutParameter", - new Object[] {paramterIndex, sqlType, typeName}); + new Object[] {parameterIndex, sqlType, typeName}); // getVendorTypeNumber() returns the same constant integer values as in java.sql.Types - registerOutParameter(paramterIndex, sqlType.getVendorTypeNumber(), typeName); + registerOutParameter(parameterIndex, sqlType.getVendorTypeNumber(), typeName); loggerExternal.exiting(getClassNameLogging(), "registerOutParameter"); } @Override - public void registerOutParameter(int paramterIndex, SQLType sqlType, int scale) throws SQLServerException { + public void registerOutParameter(int parameterIndex, SQLType sqlType, int scale) throws SQLServerException { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "registerOutParameter", - new Object[] {paramterIndex, sqlType, scale}); + new Object[] {parameterIndex, sqlType, scale}); // getVendorTypeNumber() returns the same constant integer values as in java.sql.Types - registerOutParameter(paramterIndex, sqlType.getVendorTypeNumber(), scale); + registerOutParameter(parameterIndex, sqlType.getVendorTypeNumber(), scale); loggerExternal.exiting(getClassNameLogging(), "registerOutParameter"); } @Override - public void registerOutParameter(int paramterIndex, SQLType sqlType, int precision, + public void registerOutParameter(int parameterIndex, SQLType sqlType, int precision, int scale) throws SQLServerException { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "registerOutParameter", - new Object[] {paramterIndex, sqlType, scale}); + new Object[] {parameterIndex, sqlType, scale}); // getVendorTypeNumber() returns the same constant integer values as in java.sql.Types - registerOutParameter(paramterIndex, sqlType.getVendorTypeNumber(), precision, scale); + registerOutParameter(parameterIndex, sqlType.getVendorTypeNumber(), precision, scale); loggerExternal.exiting(getClassNameLogging(), "registerOutParameter"); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java index 79df3191cb..5cc302ec73 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerClob.java @@ -19,6 +19,7 @@ import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.sql.Clob; import java.sql.SQLException; import java.text.MessageFormat; @@ -588,7 +589,7 @@ public int setString(long pos, String s) throws SQLException { * Writes len characters of str, starting at character offset, to the CLOB value that this Clob represents. The * string will overwrite the existing characters in the Clob object starting at the position pos. If the end of the * Clob value is reached while writing the given string, then the length of the Clob value will be increased to - * accomodate the extra characters. + * accommodate the extra characters. * * SQL Server behavior: If the value specified for pos is greater than then length+1 of the CLOB value then a * SQLException is thrown. @@ -776,7 +777,7 @@ public void write(byte[] b, int off, int len) throws IOException { return; try { // Convert bytes to string using US-ASCII translation. - String s = new String(b, off, len, "US-ASCII"); + String s = new String(b, off, len, StandardCharsets.US_ASCII); // Call parent's setString and update position. // setString can throw a SQLServerException, we translate diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 18142be1d8..0ba3f48d30 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -309,7 +309,7 @@ static ParsedSQLCacheItem parseAndCacheSQL(CityHash128Key key, String sql) throw * Locates statement parameters. * * @param sql - * SQL text to parse for positions of parameters to intialize. + * SQL text to parse for positions of parameters to initialize. */ private static int[] locateParams(String sql) { LinkedList parameterPositions = new LinkedList<>(); @@ -2326,8 +2326,8 @@ static int TimerRemaining(long timerExpire) { // maximum timeout the socket takes is int max. if (result > Integer.MAX_VALUE) result = Integer.MAX_VALUE; - // we have to make sure that we return atleast one ms - // we want atleast one attempt to happen with a positive timeout passed by the user. + // we have to make sure that we return at least one ms + // we want at least one attempt to happen with a positive timeout passed by the user. if (result <= 0) result = 1; return (int) result; @@ -5453,7 +5453,7 @@ protected void endRequestInternal() throws SQLException { } /** - * Replaces JDBC syntax parameter markets '?' with SQL Server paramter markers @p1, @p2 etc... + * Replaces JDBC syntax parameter markets '?' with SQL Server parameter markers @p1, @p2 etc... * * @param sql * the user's SQL @@ -5502,7 +5502,7 @@ String replaceParameterMarkers(String sqlSrc, int[] paramPositions, Parameter[] * @param nParam * the parameter number * @param name - * the paramter name + * the parameter name * @param offset * @return int */ diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java index aca757bc9f..91592c78b5 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDatabaseMetaData.java @@ -14,6 +14,8 @@ import java.sql.SQLTimeoutException; import java.text.MessageFormat; import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; @@ -80,16 +82,35 @@ CallableStatement prepare(SQLServerConnection conn) throws SQLServerException { } final class HandleAssociation { - final String databaseName; - final CallableStatement stmt; + Map statementMap; + boolean nullCatalog = false; + CallableStatement stmt; - HandleAssociation(String databaseName, CallableStatement stmt) { - this.databaseName = databaseName; - this.stmt = stmt; + HandleAssociation() { + if (null == statementMap) { + statementMap = new HashMap<>(); + } + } + + final void addToMap(String databaseName, CallableStatement stmt) { + if (null != databaseName) { + nullCatalog = false; + statementMap.put(databaseName, stmt); + } else { + nullCatalog = true; + this.stmt = stmt; + } } - final void close() throws SQLServerException { - ((SQLServerCallableStatement) stmt).close(); + final CallableStatement getMappedStatement(String databaseName) { + if (null != databaseName) { + if (null != statementMap && statementMap.containsKey(databaseName)) { + return statementMap.get(databaseName); + } + return null; + } else { + return stmt; + } } } @@ -231,6 +252,7 @@ private void checkClosed() throws SQLServerException { private static final String SS_IS_COLUMN_SET = "SS_IS_COLUMN_SET"; private static final String IS_GENERATEDCOLUMN = "IS_GENERATEDCOLUMN"; private static final String IS_AUTOINCREMENT = "IS_AUTOINCREMENT"; + private static final String SQL_KEYWORDS = createSqlKeyWords(); /** * Returns the result from a simple query. This is to be used only for internal queries without any user input. @@ -243,13 +265,15 @@ private void checkClosed() throws SQLServerException { * @throws SQLTimeoutException */ private SQLServerResultSet getResultSetFromInternalQueries(String catalog, - String query) throws SQLServerException, SQLTimeoutException { + String query) throws SQLException, SQLTimeoutException { checkClosed(); String orgCat = null; orgCat = switchCatalogs(catalog); SQLServerResultSet rs = null; try { - rs = ((SQLServerStatement) connection.createStatement()).executeQueryInternal(query); + SQLServerStatement statement = (SQLServerStatement) connection.createStatement(); + statement.closeOnCompletion(); + rs = statement.executeQueryInternal(query); } finally { if (null != orgCat) { connection.setCatalog(orgCat); @@ -265,15 +289,24 @@ private CallableStatement getCallableStatementHandle(CallableHandles request, String catalog) throws SQLServerException { CallableStatement CS = null; HandleAssociation hassoc = handleMap.get(request); - if (null == hassoc || null == hassoc.databaseName || !hassoc.databaseName.equals(catalog)) { - CS = request.prepare(connection); - hassoc = new HandleAssociation(catalog, CS); - HandleAssociation previous = handleMap.put(request, hassoc); - if (null != previous) { - previous.close(); + try { + if (null == hassoc) { + CS = request.prepare(connection); + hassoc = new HandleAssociation(); + hassoc.addToMap(catalog, CS); + } else { // hassoc != null + CS = hassoc.getMappedStatement(catalog); + // No Cached Statement yet + if (null == CS || CS.isClosed()) { + CS = request.prepare(connection); + hassoc.addToMap(catalog, CS); + } } + handleMap.put(request, hassoc); + } catch (SQLException e) { + SQLServerException.makeFromDriverError(connection, CS, e.toString(), null, false); } - return hassoc.stmt; + return CS; } /** @@ -410,12 +443,12 @@ public boolean supportsSharding() throws SQLException { } @Override - public java.sql.ResultSet getCatalogs() throws SQLServerException, SQLTimeoutException { + public java.sql.ResultSet getCatalogs() throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } checkClosed(); - // Return the orginal case instead of CAPS.removed Upper(). + // Return the original case instead of CAPS.removed Upper(). String s = "SELECT name AS TABLE_CAT FROM sys.databases order by name"; // Need // to // match @@ -531,7 +564,7 @@ private static String EscapeIDName(String inID) throws SQLServerException { // \x -> \x where x is any char other than the ones above. char ch; - // Add 2 extra chars wild guess thinking atleast one escape. + // Add 2 extra chars wild guess thinking at least one escape. StringBuilder outID = new StringBuilder(inID.length() + 2); for (int i = 0; i < inID.length(); i++) { @@ -761,7 +794,7 @@ public java.sql.ResultSet getBestRowIdentifier(String catalog, String schema, St @Override public java.sql.ResultSet getCrossReference(String cat1, String schem1, String tab1, String cat2, String schem2, - String tab2) throws SQLServerException, SQLTimeoutException { + String tab2) throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } @@ -826,7 +859,7 @@ public String getDriverVersion() throws SQLServerException { @Override public java.sql.ResultSet getExportedKeys(String cat, String schema, - String table) throws SQLServerException, SQLTimeoutException { + String table) throws SQLException, SQLTimeoutException { return getCrossReference(cat, schema, table, null, null, null); } @@ -844,11 +877,11 @@ public String getIdentifierQuoteString() throws SQLServerException { @Override public java.sql.ResultSet getImportedKeys(String cat, String schema, - String table) throws SQLServerException, SQLTimeoutException { + String table) throws SQLException, SQLTimeoutException { return getCrossReference(null, null, null, cat, schema, table); } - private ResultSet executeSPFkeys(String[] procParams) throws SQLServerException, SQLTimeoutException { + private ResultSet executeSPFkeys(String[] procParams) throws SQLException, SQLTimeoutException { String tempTableName = "@jdbc_temp_fkeys_result"; String sql = "DECLARE " + tempTableName + " table (PKTABLE_QUALIFIER sysname, " + "PKTABLE_OWNER sysname, " + "PKTABLE_NAME sysname, " + "PKCOLUMN_NAME sysname, " + "FKTABLE_QUALIFIER sysname, " @@ -858,21 +891,8 @@ private ResultSet executeSPFkeys(String[] procParams) throws SQLServerException, + " EXEC sp_fkeys ?,?,?,?,?,?;" + "SELECT t.PKTABLE_QUALIFIER AS PKTABLE_CAT, " + "t.PKTABLE_OWNER AS PKTABLE_SCHEM, " + "t.PKTABLE_NAME, " + "t.PKCOLUMN_NAME, " + "t.FKTABLE_QUALIFIER AS FKTABLE_CAT, " + "t.FKTABLE_OWNER AS FKTABLE_SCHEM, " + "t.FKTABLE_NAME, " - + "t.FKCOLUMN_NAME, " + "t.KEY_SEQ, " + "CASE s.update_referential_action " + "WHEN 1 THEN 0 " + // cascade - // - - // note - // that - // sp_fkey - // and - // sys.foreign_keys - // have - // flipped - // values - // for - // cascade - // and - // no - // action + + "t.FKCOLUMN_NAME, " + "t.KEY_SEQ, " + "CASE s.update_referential_action " + "WHEN 1 THEN 0 " + + // cascade - note that sp_fkey and sys.foreign_keys have flipped values for cascade and no action "WHEN 0 THEN 3 " + // no action "WHEN 2 THEN 2 " + // set null "WHEN 3 THEN 4 " + // set default @@ -881,6 +901,7 @@ private ResultSet executeSPFkeys(String[] procParams) throws SQLServerException, + "t.DEFERRABILITY " + "FROM " + tempTableName + " t " + "LEFT JOIN sys.foreign_keys s ON t.FK_NAME = s.name collate database_default;"; SQLServerCallableStatement cstmt = (SQLServerCallableStatement) connection.prepareCall(sql); + cstmt.closeOnCompletion(); for (int i = 0; i < 6; i++) { cstmt.setString(i + 1, procParams[i]); } @@ -986,7 +1007,7 @@ public int getMaxColumnsInTable() throws SQLServerException { } @Override - public int getMaxConnections() throws SQLServerException, SQLTimeoutException { + public int getMaxConnections() throws SQLException, SQLTimeoutException { checkClosed(); try { String s = "sp_configure 'user connections'"; @@ -1198,7 +1219,7 @@ public ResultSet getPseudoColumns(String catalog, String schemaPattern, String t } @Override - public java.sql.ResultSet getSchemas() throws SQLServerException, SQLTimeoutException { + public java.sql.ResultSet getSchemas() throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } @@ -1208,7 +1229,7 @@ public java.sql.ResultSet getSchemas() throws SQLServerException, SQLTimeoutExce } private java.sql.ResultSet getSchemasInternal(String catalog, - String schemaPattern) throws SQLServerException, SQLTimeoutException { + String schemaPattern) throws SQLException, SQLTimeoutException { String s; // The schemas that return null for catalog name, these are prebuilt @@ -1267,10 +1288,10 @@ private java.sql.ResultSet getSchemasInternal(String catalog, } else { // The prepared statement is not closed after execution. - // Yes we will "leak a server handle" per execution but the - // connection closure will release them - // + // No we will not "leak a server handle" per execution + // as the prepared statement will close as the resultset 'rs' is closed SQLServerPreparedStatement ps = (SQLServerPreparedStatement) connection.prepareStatement(s); + ps.closeOnCompletion(); ps.setString(1, schemaPattern); rs = (SQLServerResultSet) ps.executeQueryInternal(); } @@ -1300,7 +1321,38 @@ public String getSearchStringEscape() throws SQLServerException { @Override public String getSQLKeywords() throws SQLServerException { checkClosed(); - return "BACKUP,BREAK,BROWSE,BULK,CHECKPOINT,CLUSTERED,COMPUTE,CONTAINS,CONTAINSTABLE,DATABASE,DBCC,DENY,DISK,DISTRIBUTED,DUMMY,DUMP,ERRLVL,EXIT,FILE,FILLFACTOR,FREETEXT,FREETEXTTABLE,FUNCTION,HOLDLOCK,IDENTITY_INSERT,IDENTITYCOL,IF,KILL,LINENO,LOAD,NOCHECK,NONCLUSTERED,OFF,OFFSETS,OPENDATASOURCE,OPENQUERY,OPENROWSET,OPENXML,OVER,PERCENT,PLAN,PRINT,PROC,RAISERROR,READTEXT,RECONFIGURE,REPLICATION,RESTORE,RETURN,ROWCOUNT,ROWGUIDCOL,RULE,SAVE,SETUSER,SHUTDOWN,STATISTICS,TEXTSIZE,TOP,TRAN,TRIGGER,TRUNCATE,TSEQUAL,UPDATETEXT,USE,WAITFOR,WHILE,WRITETEXT"; + return SQL_KEYWORDS; + } + + private static String createSqlKeyWords() { + return "ADD,ALL,ALTER,AND,ANY,AS,ASC,AUTHORIZATION," + + "BACKUP,BEGIN,BETWEEN,BREAK,BROWSE,BULK,BY," + + "CASCADE,CASE,CHECK,CHECKPOINT,CLOSE,CLUSTERED,COALESCE,COLLATE,COLUMN,COMMIT," + + "COMPUTE,CONSTRAINT,CONTAINS,CONTAINSTABLE,CONTINUE,CONVERT,CREATE,CROSS,CURRENT," + + "CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_USER,CURSOR," + + "DATABASE,DBCC,DEALLOCATE,DECLARE,DEFAULT,DELETE,DENY,DESC,DISK," + + "DISTINCT,DISTRIBUTED,DOUBLE,DROP,DUMP," + + "ELSE,END,ERRLVL,ESCAPE,EXCEPT,EXEC,EXECUTE,EXISTS,EXIT,EXTERNAL," + + "FETCH,FILE,FILLFACTOR,FOR,FOREIGN,FREETEXT,FREETEXTTABLE,FROM,FULL,FUNCTION," + + "GOTO,GRANT,GROUP," + + "HAVING,HOLDLOCK," + + "IDENTITY,IDENTITY_INSERT,IDENTITYCOL,IF,IN,INDEX,INNER,INSERT,INTERSECT,INTO,IS," + + "JOIN," + + "KEY,KILL," + + "LEFT,LIKE,LINENO,LOAD," + + "MERGE," + + "NATIONAL,NOCHECK,NONCLUSTERED,NOT,NULL,NULLIF," + + "OF,OFF,OFFSETS,ON,OPEN,OPENDATASOURCE,OPENQUERY," + + "OPENROWSET,OPENXML,OPTION,OR,ORDER,OUTER,OVER," + + "PERCENT,PIVOT,PLAN,PRECISION,PRIMARY,PRINT,PROC,PROCEDURE,PUBLIC," + + "RAISERROR,READ,READTEXT,RECONFIGURE,REFERENCES,REPLICATION,RESTORE,RESTRICT," + + "RETURN,REVERT,REVOKE,RIGHT,ROLLBACK,ROWCOUNT,ROWGUIDCOL,RULE," + + "SAVE,SCHEMA,SECURITYAUDIT,SELECT,SEMANTICKEYPHRASETABLE,SEMANTICSIMILARITYDETAILSTABLE," + + "SEMANTICSIMILARITYTABLE,SESSION_USER,SET,SETUSER,SHUTDOWN,SOME,STATISTICS,SYSTEM_USER," + + "TABLE,TABLESAMPLE,TEXTSIZE,THEN,TO,TOP,TRAN,TRANSACTION,TRIGGER,TRUNCATE,TRY_CONVERT,TSEQUAL," + + "UNION,UNIQUE,UNPIVOT,UPDATE,UPDATETEXT,USE,USER," + + "VALUES,VARYING,VIEW," + + "WAITFOR,WHEN,WHERE,WHILE,WITH,WITHIN GROUP,WRITETEXT"; } @Override @@ -1342,7 +1394,7 @@ public java.sql.ResultSet getTablePrivileges(String catalog, String schema, } @Override - public java.sql.ResultSet getTableTypes() throws SQLServerException, SQLTimeoutException { + public java.sql.ResultSet getTableTypes() throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } @@ -1359,7 +1411,7 @@ public String getTimeDateFunctions() throws SQLServerException { } @Override - public java.sql.ResultSet getTypeInfo() throws SQLServerException, SQLTimeoutException { + public java.sql.ResultSet getTypeInfo() throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } @@ -1449,25 +1501,13 @@ public String getUserName() throws SQLServerException, SQLTimeoutException { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } checkClosed(); - SQLServerStatement s = null; - SQLServerResultSet rs = null; String result = ""; - - try { - s = (SQLServerStatement) connection.createStatement(); - rs = s.executeQueryInternal("select system_user"); + try (SQLServerStatement s = (SQLServerStatement) connection.createStatement(); + SQLServerResultSet rs = s.executeQueryInternal("select system_user")) { // Select system_user will always return a row. boolean next = rs.next(); assert next; - result = rs.getString(1); - } finally { - if (rs != null) { - rs.close(); - } - if (s != null) { - s.close(); - } } return result; } @@ -2110,7 +2150,7 @@ public boolean supportsBatchUpdates() throws SQLServerException { @Override public java.sql.ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, - int[] types) throws SQLServerException, SQLTimeoutException { + int[] types) throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } @@ -2212,7 +2252,7 @@ public boolean supportsResultSetHoldability(int holdability) throws SQLServerExc @Override public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, - String attributeNamePattern) throws SQLServerException, SQLTimeoutException { + String attributeNamePattern) throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } @@ -2243,7 +2283,7 @@ public ResultSet getAttributes(String catalog, String schemaPattern, String type @Override public ResultSet getSuperTables(String catalog, String schemaPattern, - String tableNamePattern) throws SQLServerException, SQLTimeoutException { + String tableNamePattern) throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } @@ -2257,7 +2297,7 @@ public ResultSet getSuperTables(String catalog, String schemaPattern, @Override public ResultSet getSuperTypes(String catalog, String schemaPattern, - String typeNamePattern) throws SQLServerException, SQLTimeoutException { + String typeNamePattern) throws SQLException, SQLTimeoutException { if (loggerExternal.isLoggable(Level.FINER) && Util.IsActivityTraceOn()) { loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString()); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java index fc3e6a424b..be19694f5e 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerException.java @@ -126,7 +126,7 @@ private void logException(Object o, String errText, boolean bStack) { exLogger.fine(sb.toString()); } } - if (errText.equals(SQLServerException.getErrString("R_queryTimedOut"))) { + if (SQLServerException.getErrString("R_queryTimedOut").equals(errText)) { this.setDriverErrorCode(SQLServerException.ERROR_QUERY_TIMEOUT); } } @@ -366,7 +366,7 @@ static String generateStateCode(SQLServerConnection con, int errNum, int databas * Appends ClientConnectionId to an error message if applicable. * * @param errMsg - * - the orginal error message. + * - the original error message. * @param conn * - the SQLServerConnection object * @return error string concated by ClientConnectionId(in string format) if applicable, otherwise, return original diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 31b4947817..41844f8134 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -389,7 +389,7 @@ private boolean buildPreparedStrings(Parameter[] params, boolean renewDefinition * True if renewing parameter definition, False otherwise * @throws SQLServerException * when an error occurs. - * @return the required data type defintions. + * @return the required data type definitions. */ private String buildParamTypeDefinitions(Parameter[] params, boolean renewDefinition) throws SQLServerException { StringBuilder sb = new StringBuilder(); @@ -543,7 +543,7 @@ final void doExecutePreparedStatement(PrepStmtExecCmd command) throws SQLServerE if ((Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection)) && (0 < inOutParam.length) && !isInternalEncryptionQuery) { - // retrieve paramater encryption metadata if they are not retrieved yet + // retrieve parameter encryption metadata if they are not retrieved yet if (!encryptionMetadataIsRetrieved) { getParameterEncryptionMetadata(inOutParam); encryptionMetadataIsRetrieved = true; @@ -1101,7 +1101,7 @@ private ResultSet buildExecuteMetaData() throws SQLServerException { * The index of the parameter to set starting at 1. * @return A reference the to Parameter object created or referenced. * @exception SQLServerException - * The index specified was outside the number of paramters for the statement. + * The index specified was outside the number of parameters for the statement. */ final Parameter setterGetParam(int index) throws SQLServerException { if (index < 1 || index > inOutParam.length) { @@ -1178,33 +1178,33 @@ public final void setAsciiStream(int parameterIndex, InputStream x, long length) } @Override - public final void setBigDecimal(int paramterIndex, BigDecimal x) throws SQLServerException { + public final void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLServerException { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) - loggerExternal.entering(getClassNameLogging(), "setBigDecimal", new Object[] {paramterIndex, x}); + loggerExternal.entering(getClassNameLogging(), "setBigDecimal", new Object[] {parameterIndex, x}); checkClosed(); - setValue(paramterIndex, JDBCType.DECIMAL, x, JavaType.BIGDECIMAL, false); + setValue(parameterIndex, JDBCType.DECIMAL, x, JavaType.BIGDECIMAL, false); loggerExternal.exiting(getClassNameLogging(), "setBigDecimal"); } @Override - public final void setBigDecimal(int paramterIndex, BigDecimal x, int precision, + public final void setBigDecimal(int parameterIndex, BigDecimal x, int precision, int scale) throws SQLServerException { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "setBigDecimal", - new Object[] {paramterIndex, x, precision, scale}); + new Object[] {parameterIndex, x, precision, scale}); checkClosed(); - setValue(paramterIndex, JDBCType.DECIMAL, x, JavaType.BIGDECIMAL, precision, scale, false); + setValue(parameterIndex, JDBCType.DECIMAL, x, JavaType.BIGDECIMAL, precision, scale, false); loggerExternal.exiting(getClassNameLogging(), "setBigDecimal"); } @Override - public final void setBigDecimal(int paramterIndex, BigDecimal x, int precision, int scale, + public final void setBigDecimal(int parameterIndex, BigDecimal x, int precision, int scale, boolean forceEncrypt) throws SQLServerException { if (loggerExternal.isLoggable(java.util.logging.Level.FINER)) loggerExternal.entering(getClassNameLogging(), "setBigDecimal", - new Object[] {paramterIndex, x, precision, scale, forceEncrypt}); + new Object[] {parameterIndex, x, precision, scale, forceEncrypt}); checkClosed(); - setValue(paramterIndex, JDBCType.DECIMAL, x, JavaType.BIGDECIMAL, precision, scale, forceEncrypt); + setValue(parameterIndex, JDBCType.DECIMAL, x, JavaType.BIGDECIMAL, precision, scale, forceEncrypt); loggerExternal.exiting(getClassNameLogging(), "setBigDecimal"); } @@ -2003,6 +2003,9 @@ public int[] executeBatch() throws SQLServerException, BatchUpdateException, SQL } SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); + SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); + option.setBulkCopyTimeout(queryTimeout); + bcOperation.setBulkCopyOptions(option); bcOperation.setDestinationTableName(tableName); bcOperation.setStmtColumnEncriptionSetting(this.getStmtColumnEncriptionSetting()); bcOperation.setDestinationTableMetadata(rs); @@ -2157,6 +2160,9 @@ public long[] executeLargeBatch() throws SQLServerException, BatchUpdateExceptio } SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); + SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); + option.setBulkCopyTimeout(queryTimeout); + bcOperation.setBulkCopyOptions(option); bcOperation.setDestinationTableName(tableName); bcOperation.setStmtColumnEncriptionSetting(this.getStmtColumnEncriptionSetting()); bcOperation.setDestinationTableMetadata(rs); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java index 612c44ab33..e163219e80 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerResultSet.java @@ -793,7 +793,7 @@ public boolean relative(int rows) throws SQLException { checkClosed(); // From JDBC spec: - // Throws SQLException if (1) there is no curent row or (2) + // Throws SQLException if (1) there is no current row or (2) // the type of this ResultSet object is TYPE_FORWARD_ONLY. verifyResultSetIsScrollable(); verifyResultSetHasCurrentRow(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java index c2c269053d..d0ae5e25b5 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java @@ -439,7 +439,7 @@ boolean onDone(TDSReader tdsReader) throws SQLServerException { int nFetchDirection; /** - * True is the statment is closed + * True is the statement is closed */ boolean bIsClosed; @@ -948,7 +948,7 @@ final void resetForReexecute() throws SQLServerException { * Determines if the SQL is a SELECT. * * @param sql - * The statment SQL. + * The statement SQL. * @return True if the statement is a select. */ final boolean isSelect(String sql) throws SQLServerException { @@ -966,7 +966,7 @@ final boolean isSelect(String sql) throws SQLServerException { * Determine if the SQL is a INSERT. * * @param sql - * The statment SQL. + * The statement SQL. * @return True if the statement is an insert. */ final boolean isInsert(String sql) throws SQLServerException { diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java b/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java index 8d314b08e9..1b60a9feef 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/StreamTabName.java @@ -34,7 +34,7 @@ void applyTo(Column[] columns, int numTables) throws SQLServerException { // Read in all of the multi-part table names. The number of table // names to expect is determined in advance. It is computed as a side - // effect of processing the COLINFO token that preceeds this TABNAME token. + // effect of processing the COLINFO token that preceds this TABNAME token. SQLIdentifier[] tableNames = new SQLIdentifier[numTables]; for (int i = 0; i < numTables; i++) tableNames[i] = tdsReader.readSQLIdentifier(); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java index a9557c2c78..92bf03d6c1 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java @@ -431,7 +431,7 @@ else if ((-1 != rightQuote.indexOf(testchar)) || (-1 != leftQuote.indexOf(testch } /* - * parsing the multipart identifer string. paramaters: name - string to parse leftquote: set of characters which are + * parsing the multipart identifer string. parameters: name - string to parse leftquote: set of characters which are * valid quoteing characters to initiate a quote rightquote: set of characters which are valid to stop a quote, * array index's correspond to the the leftquote array. separator: separator to use limit: number of names to parse * out removequote:to remove the quotes on the returned string diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/dataclassification/SensitivityProperty.java b/src/main/java/com/microsoft/sqlserver/jdbc/dataclassification/SensitivityProperty.java index 1c8846deb5..d4024a9fcb 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/dataclassification/SensitivityProperty.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/dataclassification/SensitivityProperty.java @@ -18,7 +18,7 @@ public class SensitivityProperty { * @param label * Label as received from SQL Server for this SensitivityProperty * @param informationType - * InformationType as recieved from SQL Server for this SensitivityProperty + * InformationType as received from SQL Server for this SensitivityProperty */ public SensitivityProperty(Label label, InformationType informationType) { this.label = label; diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/dns/DNSKerberosLocator.java b/src/main/java/com/microsoft/sqlserver/jdbc/dns/DNSKerberosLocator.java index 11e85ebd80..cdcdbb5359 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/dns/DNSKerberosLocator.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/dns/DNSKerberosLocator.java @@ -9,7 +9,6 @@ import javax.naming.NameNotFoundException; import javax.naming.NamingException; - /** * Represents a DNS Kerberos Locator */ @@ -18,7 +17,9 @@ public final class DNSKerberosLocator { private DNSKerberosLocator() {} /** - * Returns whether a realm is valid. + * Returns whether a realm is valid by retrieving the KDC list in DNS SRV records. + * This will only work if DNS lookup is setup properly or the realms are properly defined in krb5 config file. + * Otherwise this will fail since the realm cannot be found. * * @param realmName * the realm to test @@ -37,6 +38,7 @@ public static boolean isRealmValid(String realmName) throws NamingException { Set records = DNSUtilities.findSrvRecords("_kerberos._udp." + realmName); return !records.isEmpty(); } catch (NameNotFoundException wrongDomainException) { + // config error - domain controller cannot be located via DNS return false; } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java index ae3693af54..657cb7e798 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/dtv.java @@ -19,6 +19,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.sql.Blob; import java.sql.Clob; import java.sql.SQLException; @@ -2193,11 +2194,7 @@ void execute(DTV dtv, InputStream inputStreamValue) throws SQLServerException { // If the stream is to be sent as Unicode, then assume it's an ASCII stream if (JDBCType.NCHAR == jdbcType || JDBCType.NVARCHAR == jdbcType || JDBCType.LONGNVARCHAR == jdbcType) { Reader readerValue = null; - try { - readerValue = new InputStreamReader(inputStreamValue, "US-ASCII"); - } catch (UnsupportedEncodingException ex) { - throw new SQLServerException(ex.getMessage(), null, 0, ex); - } + readerValue = new InputStreamReader(inputStreamValue, StandardCharsets.US_ASCII); dtv.setValue(readerValue, JavaType.READER); diff --git a/src/main/java/mssql/googlecode/concurrentlinkedhashmap/ConcurrentLinkedHashMap.java b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/ConcurrentLinkedHashMap.java index ba48e21cdb..87ccd10d34 100644 --- a/src/main/java/mssql/googlecode/concurrentlinkedhashmap/ConcurrentLinkedHashMap.java +++ b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/ConcurrentLinkedHashMap.java @@ -15,12 +15,12 @@ */ package mssql.googlecode.concurrentlinkedhashmap; -import static mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.DrainStatus.IDLE; -import static mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.DrainStatus.PROCESSING; -import static mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.DrainStatus.REQUIRED; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableMap; import static java.util.Collections.unmodifiableSet; +import static mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.DrainStatus.IDLE; +import static mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.DrainStatus.PROCESSING; +import static mssql.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.DrainStatus.REQUIRED; import java.io.InvalidObjectException; import java.io.ObjectInputStream; diff --git a/src/main/java/mssql/googlecode/concurrentlinkedhashmap/Weighers.java b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/Weighers.java index 469977a11d..b6de5f12b7 100644 --- a/src/main/java/mssql/googlecode/concurrentlinkedhashmap/Weighers.java +++ b/src/main/java/mssql/googlecode/concurrentlinkedhashmap/Weighers.java @@ -19,7 +19,6 @@ import java.io.Serializable; import java.util.Collection; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/src/samples/README.md b/src/samples/README.md index 444d5086a4..c06c9ab8c9 100644 --- a/src/samples/README.md +++ b/src/samples/README.md @@ -25,7 +25,7 @@ The following samples are available: 5. datatypes * **BasicDataTypes** - Demonstrates how to retrieve and update basic SQL Server data type values. * **SqlXmlDataType** - Demonstrates how to store and retrieve XML data as well as how to parse XML data with the SQLXML Java data type. - * **SpatialDatatypes** - Demonstrates how to store and retreive Spatial Data as well how to parse data using `Geometry` and `Geography` Java types defined by Microsoft JDBC Driver. + * **SpatialDatatypes** - Demonstrates how to store and retrieve Spatial Data as well how to parse data using `Geometry` and `Geography` Java types defined by Microsoft JDBC Driver. 6. resultsets * **CacheRS** - Demonstrates how to retrieve a large set of data and control the amount of data that is fetched and cached on the client diff --git a/src/samples/constrained/src/main/java/ConstrainedDelegation.java b/src/samples/constrained/src/main/java/ConstrainedDelegation.java index 11f39b611e..3e952f86bc 100644 --- a/src/samples/constrained/src/main/java/ConstrainedDelegation.java +++ b/src/samples/constrained/src/main/java/ConstrainedDelegation.java @@ -74,7 +74,7 @@ public static void main(String... args) throws Exception { // Create a connection for target service thanks S4U2proxy mechanism try (Connection con = createConnection(impersonatedUserCreds)) { - System.out.println("Connection succesfully: " + con); + System.out.println("Connection successfully: " + con); } } 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 3f330857b8..2a5fd18fcc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -1,6 +1,6 @@ /* * Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made - * available under the terms of the MIT License. See the LICENSE file in the project root for more information. + * available under the terms of the MIT License. See the LICENSE file in the project root for more AEInformation. */ package com.microsoft.sqlserver.jdbc.AlwaysEncrypted; @@ -20,6 +20,7 @@ import java.sql.Timestamp; import java.util.LinkedList; import java.util.Properties; +import java.util.UUID; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -28,6 +29,7 @@ import org.opentest4j.TestAbortedException; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerConnection; @@ -36,6 +38,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatementColumnEncryptionSetting; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; @@ -57,23 +60,25 @@ public class AESetup extends AbstractTest { static final String cmkName = "JDBC_CMK"; static final String cekName = "JDBC_CEK"; static final String secretstrJks = "password"; - static final String charTable = "JDBCEncryptedCharTable"; - static final String binaryTable = "JDBCEncryptedBinaryTable"; - static final String dateTable = "JDBCEncryptedDateTable"; - static final String numericTable = "JDBCEncryptedNumericTable"; - static final String scaleDateTable = "JDBCEncryptedScaleDateTable"; - static final String uid = "171fbe25-4331-4765-a838-b2e3eea3e7ea"; + static String charTable = RandomUtil.getIdentifier("JDBCEncryptedChar"); + static String binaryTable = RandomUtil.getIdentifier("JDBCEncryptedBinary"); + static String dateTable = RandomUtil.getIdentifier("JDBCEncryptedDate"); + static String numericTable = RandomUtil.getIdentifier("JDBCEncryptedNumeric"); + static String scaleDateTable = RandomUtil.getIdentifier("JDBCEncryptedScaleDate"); + + static final String uid = UUID.randomUUID().toString(); static String filePath = null; static String thumbprint = null; - static SQLServerConnection con = null; - static SQLServerStatement stmt = null; static String keyPath = null; static String javaKeyAliases = null; static String OS = System.getProperty("os.name").toLowerCase(); static SQLServerColumnEncryptionKeyStoreProvider storeProvider = null; static SQLServerStatementColumnEncryptionSetting stmtColEncSetting = null; + static String AETestConnectionString; + + static Properties AEInfo; /** * Create connection, statement and generate path of resource file @@ -87,9 +92,8 @@ public static void setUpConnection() throws TestAbortedException, Exception { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - String AETestConnectionString = connectionString + ";sendTimeAsDateTime=false"; + AETestConnectionString = connectionString + ";sendTimeAsDateTime=false"; readFromFile(javaKeyStoreInputFile, "Alias name"); - try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { dropCEK(stmt); @@ -100,14 +104,12 @@ public static void setUpConnection() throws TestAbortedException, Exception { storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, secretstrJks.toCharArray()); stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.Enabled; - Properties info = new Properties(); - info.setProperty("ColumnEncryptionSetting", "Enabled"); - info.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); - info.setProperty("keyStoreLocation", keyPath); - info.setProperty("keyStoreSecret", secretstrJks); + AEInfo = new Properties(); + AEInfo.setProperty("ColumnEncryptionSetting", "Enabled"); + AEInfo.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); + AEInfo.setProperty("keyStoreLocation", keyPath); + AEInfo.setProperty("keyStoreSecret", secretstrJks); - con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, info); - stmt = (SQLServerStatement) con.createStatement(); createCMK(keyStoreName, javaKeyAliases); createCEK(storeProvider); } @@ -119,11 +121,17 @@ public static void setUpConnection() throws TestAbortedException, Exception { * @throws SQLException */ @AfterAll - public static void dropAll() throws SQLException { - dropTables(stmt); - dropCEK(stmt); - dropCMK(stmt); - TestUtils.close(null, stmt, con); + public static void dropAll() throws Exception { + try (DBConnection con = new DBConnection(connectionString)) { + assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); + } + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + dropCEK(stmt); + dropCMK(stmt); + } } /** @@ -162,7 +170,8 @@ private static void readFromFile(String inputFile, String lookupValue) throws IO * @throws SQLException */ protected static void createBinaryTable() throws SQLException { - String sql = "create table " + binaryTable + " (" + "PlainBinary binary(20) null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " (" + + "PlainBinary binary(20) null," + "RandomizedBinary binary(20) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicBinary binary(20) ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -194,7 +203,8 @@ protected static void createBinaryTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -208,7 +218,8 @@ protected static void createBinaryTable() throws SQLException { * @throws SQLException */ protected static void createCharTable() throws SQLException { - String sql = "create table " + charTable + " (" + "PlainChar char(20) null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (" + + "PlainChar char(20) null," + "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -264,7 +275,8 @@ protected static void createCharTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -278,7 +290,7 @@ protected static void createCharTable() throws SQLException { * @throws SQLException */ protected void createDateTable() throws SQLException { - String sql = "create table " + dateTable + " (" + "PlainDate date null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + "PlainDate date null," + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicDate date ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -316,7 +328,8 @@ protected void createDateTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -330,7 +343,7 @@ protected void createDateTable() throws SQLException { * @throws SQLException */ protected void createDatePrecisionTable(int scale) throws SQLException { - String sql = "create table " + dateTable + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" // 1 + "PlainDatetime2 datetime2(" + scale + ") null," + "RandomizedDatetime2 datetime2(" + scale + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -376,7 +389,8 @@ protected void createDatePrecisionTable(int scale) throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -390,7 +404,7 @@ protected void createDatePrecisionTable(int scale) throws SQLException { * @throws SQLException */ protected static void createDateScaleTable() throws SQLException { - String sql = "create table " + scaleDateTable + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + " (" + "PlainDatetime2 datetime2(2) null," + "RandomizedDatetime2 datetime2(2) ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -412,7 +426,8 @@ protected static void createDateScaleTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -426,7 +441,7 @@ protected static void createDateScaleTable() throws SQLException { * @throws SQLException */ protected static void createNumericTable() throws SQLException { - String sql = "create table " + numericTable + " (" + "PlainBit bit null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainBit bit null," + "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -524,7 +539,8 @@ protected static void createNumericTable() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -538,8 +554,8 @@ protected static void createNumericTable() throws SQLException { * @throws SQLException */ protected void createNumericPrecisionTable(int floatPrecision, int precision, int scale) throws SQLException { - String sql = "create table " + numericTable + " (" + "PlainFloat float(" + floatPrecision + ") null," - + "RandomizedFloat float(" + floatPrecision + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainFloat float(" + + floatPrecision + ") null," + "RandomizedFloat float(" + floatPrecision + ") ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicFloat float(" + floatPrecision + ") ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -561,7 +577,8 @@ protected void createNumericPrecisionTable(int floatPrecision, int precision, in + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -684,7 +701,7 @@ protected static LinkedList createTemporalTypes(boolean nullable) { */ private static void createCMK(String keyStoreName, String keyPath) throws SQLException { try (SQLServerConnection con = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String sql = " if not exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')" + " begin" + " CREATE COLUMN MASTER KEY " + cmkName + " WITH (KEY_STORE_PROVIDER_NAME = '" @@ -702,7 +719,7 @@ private static void createCMK(String keyStoreName, String keyPath) throws SQLExc */ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storeProvider) throws SQLException { try (SQLServerConnection con = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { String letters = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] valuesDefault = letters.getBytes(); @@ -721,10 +738,10 @@ private static void createCEK(SQLServerColumnEncryptionKeyStoreProvider storePro * @throws SQLException */ protected static void dropTables(SQLServerStatement statement) throws SQLException { - TestUtils.dropTableIfExists(numericTable, statement); - TestUtils.dropTableIfExists(charTable, statement); - TestUtils.dropTableIfExists(binaryTable, statement); - TestUtils.dropTableIfExists(dateTable, statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(binaryTable), statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateTable), statement); } /** @@ -734,11 +751,11 @@ protected static void dropTables(SQLServerStatement statement) throws SQLExcepti * @throws SQLException */ protected static void populateBinaryNormalCase(LinkedList byteValues) throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; try (SQLServerConnection con = (SQLServerConnection) DriverManager - .getConnection(connectionString + ";sendTimeAsDateTime=false", info); + .getConnection(connectionString + ";sendTimeAsDateTime=false", AEInfo); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { @@ -798,10 +815,11 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th * @throws SQLException */ protected static void populateBinarySetObject(LinkedList byteValues) throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; - - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // binary(20) @@ -860,11 +878,13 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr * @throws SQLException */ protected static void populateBinarySetObjectWithJDBCType(LinkedList byteValues) throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // binary(20) for (int i = 1; i <= 3; i++) { @@ -921,11 +941,13 @@ protected static void populateBinarySetObjectWithJDBCType(LinkedList byt * @throws SQLException */ protected static void populateBinaryNullCase() throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" - + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // binary for (int i = 1; i <= 3; i++) { @@ -958,11 +980,13 @@ protected static void populateBinaryNullCase() throws SQLException { * @throws SQLException */ protected static void populateCharNormalCase(String[] charValues) throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // char for (int i = 1; i <= 3; i++) { @@ -1024,10 +1048,12 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce * @throws SQLException */ protected static void populateCharSetObject(String[] charValues) throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1086,10 +1112,12 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep * @throws SQLException */ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1147,10 +1175,12 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th * @throws SQLException */ protected static void populateCharNullCase() throws SQLException { - String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // char @@ -1200,10 +1230,12 @@ protected static void populateCharNullCase() throws SQLException { * @throws SQLException */ protected static void populateDateNormalCase(LinkedList dateValues) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1247,9 +1279,12 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro * @throws SQLException */ protected static void populateDateScaleNormalCase(LinkedList dateValues) throws SQLException { - String sql = "insert into " + scaleDateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // datetime2(2) @@ -1279,14 +1314,13 @@ protected static void populateDateScaleNormalCase(LinkedList dateValues) * @throws SQLException */ protected static void populateDateSetObject(LinkedList dateValues, String setter) throws SQLException { - if (setter.equalsIgnoreCase("setwithJDBCType")) { - skipTestForJava7(); - } - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1349,10 +1383,12 @@ else if (setter.equalsIgnoreCase("setwithJDBCType")) * @throws SQLException */ protected void populateDateSetObjectNull() throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1395,10 +1431,12 @@ protected void populateDateSetObjectNull() throws SQLException { * @throws SQLException */ protected static void populateDateNullCase() throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // date @@ -1442,11 +1480,13 @@ protected static void populateDateNullCase() throws SQLException { * @throws SQLException */ protected static void populateNumeric(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1550,11 +1590,13 @@ protected static void populateNumeric(String[] values) throws SQLException { * @throws SQLException */ protected static void populateNumericSetObject(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1658,11 +1700,13 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept * @throws SQLException */ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1765,11 +1809,13 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr * @throws SQLException */ protected static void populateNumericSetObjectNull() throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1863,13 +1909,15 @@ protected static void populateNumericSetObjectNull() throws SQLException { * @throws SQLException */ protected static void populateNumericNullCase(String[] values) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -1962,13 +2010,15 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti * @throws SQLException */ protected static void populateNumericNormalCase(String[] numericValues) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?" + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, stmtColEncSetting)) { // bit @@ -2089,13 +2139,4 @@ private static void dropCMK(SQLServerStatement stmt) throws SQLException { stmt.execute(cekSql); } - /** - * Skip test if the client is using Java 7 or does not support JDBC 4.2. - * - * @throws SQLException - * @throws TestAbortedException - */ - protected static void skipTestForJava7() throws TestAbortedException, SQLException { - assumeTrue(TestUtils.supportJDBC42(con)); // With Java 7, skip tests for JDBCType. - } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java index b23c091c79..33d41a9313 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -7,9 +7,11 @@ 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.math.BigDecimal; import java.sql.Date; +import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; @@ -23,11 +25,16 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; +import com.microsoft.sqlserver.testframework.DBConnection; import microsoft.sql.DateTimeOffset; @@ -39,37 +46,32 @@ @RunWith(JUnitPlatform.class) public class CallableStatementTest extends AESetup { - private static String multiStatementsProcedure = "multiStatementsProcedure"; - - private static String inputProcedure = "inputProcedure"; - private static String inputProcedure2 = "inputProcedure2"; - - private static String outputProcedure = "outputProcedure"; - private static String outputProcedure2 = "outputProcedure2"; - private static String outputProcedure3 = "outputProcedure3"; - private static String outputProcedureChar = "outputProcedureChar"; - private static String outputProcedureNumeric = "outputProcedureNumeric"; - private static String outputProcedureBinary = "outputProcedureBinary"; - private static String outputProcedureDate = "outputProcedureDate"; - private static String MixedProcedureDateScale = "outputProcedureDateScale"; - private static String outputProcedureBatch = "outputProcedureBatch"; - private static String outputProcedure4 = "outputProcedure4"; - - private static String inoutProcedure = "inoutProcedure"; - - private static String mixedProcedure = "mixedProcedure"; - private static String mixedProcedure2 = "mixedProcedure2"; - private static String mixedProcedure3 = "mixedProcedure3"; - private static String mixedProcedureNumericPrcisionScale = "mixedProcedureNumericPrcisionScale"; - - private static String table1 = "StoredProcedureTable1"; - private static String table2 = "StoredProcedureTable2"; - private static String table3 = "StoredProcedureTable3"; - private static String table4 = "StoredProcedureTable4"; - private static String table5 = "StoredProcedureTable5"; - private static String table6 = "StoredProcedureTable6"; - - static final String uid = "171fbe25-4331-4765-a838-b2e3eea3e7ea"; + private static String multiStatementsProcedure = RandomUtil.getIdentifier("multiStatementsProcedure"); + private static String inputProcedure = RandomUtil.getIdentifier("inputProcedure"); + private static String inputProcedure2 = RandomUtil.getIdentifier("inputProcedure2"); + private static String outputProcedure = RandomUtil.getIdentifier("outputProcedure"); + private static String outputProcedure2 = RandomUtil.getIdentifier("outputProcedure2"); + private static String outputProcedure3 = RandomUtil.getIdentifier("outputProcedure3"); + private static String outputProcedure4 = RandomUtil.getIdentifier("outputProcedure4"); + private static String outputProcedureChar = RandomUtil.getIdentifier("outputProcedureChar"); + private static String outputProcedureNumeric = RandomUtil.getIdentifier("outputProcedureNumeric"); + private static String outputProcedureBinary = RandomUtil.getIdentifier("outputProcedureBinary"); + private static String outputProcedureDate = RandomUtil.getIdentifier("outputProcedureDate"); + private static String outputProcedureDateScale = RandomUtil.getIdentifier("outputProcedureDateScale"); + private static String outputProcedureBatch = RandomUtil.getIdentifier("outputProcedureBatch"); + private static String inoutProcedure = RandomUtil.getIdentifier("inoutProcedure"); + private static String mixedProcedure = RandomUtil.getIdentifier("mixedProcedure"); + private static String mixedProcedure2 = RandomUtil.getIdentifier("mixedProcedure2"); + private static String mixedProcedure3 = RandomUtil.getIdentifier("mixedProcedure3"); + private static String mixedProcedureNumericPrcisionScale = RandomUtil + .getIdentifier("mixedProcedureNumericPrcisionScale"); + + private static String table1 = RandomUtil.getIdentifier("StoredProcedure_table1"); + private static String table2 = RandomUtil.getIdentifier("StoredProcedure_table2"); + private static String table3 = RandomUtil.getIdentifier("StoredProcedure_table3"); + private static String table4 = RandomUtil.getIdentifier("StoredProcedure_table4"); + private static String table5 = RandomUtil.getIdentifier("StoredProcedure_table5"); + private static String table6 = RandomUtil.getIdentifier("StoredProcedure_table6"); private static String[] numericValues; private static LinkedList byteValues; @@ -84,7 +86,11 @@ public class CallableStatementTest extends AESetup { * @throws SQLException */ @BeforeAll - public static void initCallableStatementTest() throws SQLException { + public static void initCallableStatementTest() throws Exception { + try (DBConnection con = new DBConnection(connectionString)) { + assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); + } + dropTables(); numericValues = createNumericValues(nullable); @@ -110,8 +116,12 @@ public static void initCallableStatementTest() throws SQLException { } @AfterAll - public static void dropAll() throws SQLException { + public static void dropAll() throws Exception { + try (DBConnection con = new DBConnection(connectionString)) { + assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); + } dropTables(); + dropProcedures(); } @Test @@ -123,51 +133,63 @@ public void testMultiInsertionSelection() throws SQLException { @Test public void testInputProcedureNumeric() throws SQLException { createInputProcedure(); - testInputProcedure("{call " + inputProcedure + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}", numericValues); + testInputProcedure( + "{call " + AbstractSQLGenerator.escapeIdentifier(inputProcedure) + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}", + numericValues); } @Test public void testInputProcedureChar() throws SQLException { createInputProcedure2(); - testInputProcedure2("{call " + inputProcedure2 + "(?,?,?,?,?,?,?,?)}"); + testInputProcedure2("{call " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2) + "(?,?,?,?,?,?,?,?)}"); } @Test public void testEncryptedOutputNumericParams() throws SQLException { createOutputProcedure(); - testOutputProcedureRandomOrder("{call " + outputProcedure + "(?,?,?,?,?,?,?)}", numericValues); - testOutputProcedureInorder("{call " + outputProcedure + "(?,?,?,?,?,?,?)}", numericValues); - testOutputProcedureReverseOrder("{call " + outputProcedure + "(?,?,?,?,?,?,?)}", numericValues); - testOutputProcedureRandomOrder("exec " + outputProcedure + " ?,?,?,?,?,?,?", numericValues); + testOutputProcedureRandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + "(?,?,?,?,?,?,?)}", numericValues); + testOutputProcedureInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + "(?,?,?,?,?,?,?)}", numericValues); + testOutputProcedureReverseOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + "(?,?,?,?,?,?,?)}", numericValues); + testOutputProcedureRandomOrder( + "exec " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + " ?,?,?,?,?,?,?", numericValues); } @Test public void testUnencryptedAndEncryptedNumericOutputParams() throws SQLException { createOutputProcedure2(); - testOutputProcedure2RandomOrder("{call " + outputProcedure2 + "(?,?,?,?,?,?,?,?,?,?)}", numericValues); - testOutputProcedure2Inorder("{call " + outputProcedure2 + "(?,?,?,?,?,?,?,?,?,?)}", numericValues); - testOutputProcedure2ReverseOrder("{call " + outputProcedure2 + "(?,?,?,?,?,?,?,?,?,?)}", numericValues); + testOutputProcedure2RandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + "(?,?,?,?,?,?,?,?,?,?)}", + numericValues); + testOutputProcedure2Inorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + "(?,?,?,?,?,?,?,?,?,?)}", + numericValues); + testOutputProcedure2ReverseOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + "(?,?,?,?,?,?,?,?,?,?)}", + numericValues); } @Test public void testEncryptedOutputParamsFromDifferentTables() throws SQLException { createOutputProcedure3(); - testOutputProcedure3RandomOrder("{call " + outputProcedure3 + "(?,?)}"); - testOutputProcedure3Inorder("{call " + outputProcedure3 + "(?,?)}"); - testOutputProcedure3ReverseOrder("{call " + outputProcedure3 + "(?,?)}"); + testOutputProcedure3RandomOrder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + "(?,?)}"); + testOutputProcedure3Inorder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + "(?,?)}"); + testOutputProcedure3ReverseOrder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + "(?,?)}"); } @Test public void testInOutProcedure() throws SQLException { createInOutProcedure(); - testInOutProcedure("{call " + inoutProcedure + "(?)}"); - testInOutProcedure("exec " + inoutProcedure + " ?"); + testInOutProcedure("{call " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure) + "(?)}"); + testInOutProcedure("exec " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure) + " ?"); } @Test public void testMixedProcedure() throws SQLException { createMixedProcedure(); - testMixedProcedure("{ ? = call " + mixedProcedure + "(?,?,?)}"); + testMixedProcedure("{ ? = call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure) + "(?,?,?)}"); } @Test @@ -175,67 +197,82 @@ public void testUnencryptedAndEncryptedIOParams() throws SQLException { // unencrypted input and output parameter // encrypted input and output parameter createMixedProcedure2(); - testMixedProcedure2RandomOrder("{call " + mixedProcedure2 + "(?,?,?,?)}"); - testMixedProcedure2Inorder("{call " + mixedProcedure2 + "(?,?,?,?)}"); + testMixedProcedure2RandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2) + "(?,?,?,?)}"); + testMixedProcedure2Inorder("{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2) + "(?,?,?,?)}"); } @Test public void testUnencryptedIOParams() throws SQLException { createMixedProcedure3(); - testMixedProcedure3RandomOrder("{call " + mixedProcedure3 + "(?,?,?,?)}"); - testMixedProcedure3Inorder("{call " + mixedProcedure3 + "(?,?,?,?)}"); - testMixedProcedure3ReverseOrder("{call " + mixedProcedure3 + "(?,?,?,?)}"); + testMixedProcedure3RandomOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + "(?,?,?,?)}"); + testMixedProcedure3Inorder("{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + "(?,?,?,?)}"); + testMixedProcedure3ReverseOrder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + "(?,?,?,?)}"); } @Test public void testVariousIOParams() throws SQLException { createMixedProcedureNumericPrcisionScale(); - testMixedProcedureNumericPrcisionScaleInorder("{call " + mixedProcedureNumericPrcisionScale + "(?,?,?,?)}"); + testMixedProcedureNumericPrcisionScaleInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale) + "(?,?,?,?)}"); testMixedProcedureNumericPrcisionScaleParameterName( - "{call " + mixedProcedureNumericPrcisionScale + "(?,?,?,?)}"); + "{call " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale) + "(?,?,?,?)}"); } @Test public void testOutputProcedureChar() throws SQLException { createOutputProcedureChar(); - testOutputProcedureCharInorder("{call " + outputProcedureChar + "(?,?,?,?,?,?,?,?,?)}"); - testOutputProcedureCharInorderObject("{call " + outputProcedureChar + "(?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureCharInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar) + "(?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureCharInorderObject( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar) + "(?,?,?,?,?,?,?,?,?)}"); } @Test public void testOutputProcedureNumeric() throws SQLException { createOutputProcedureNumeric(); - testOutputProcedureNumericInorder("{call " + outputProcedureNumeric + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); - testcoerctionsOutputProcedureNumericInorder( - "{call " + outputProcedureNumeric + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureNumericInorder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric) + + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testcoerctionsOutputProcedureNumericInorder("{call " + + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric) + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); } @Test public void testOutputProcedureBinary() throws SQLException { createOutputProcedureBinary(); - testOutputProcedureBinaryInorder("{call " + outputProcedureBinary + "(?,?,?,?,?)}"); - testOutputProcedureBinaryInorderObject("{call " + outputProcedureBinary + "(?,?,?,?,?)}"); - testOutputProcedureBinaryInorderString("{call " + outputProcedureBinary + "(?,?,?,?,?)}"); + testOutputProcedureBinaryInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + "(?,?,?,?,?)}"); + testOutputProcedureBinaryInorderObject( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + "(?,?,?,?,?)}"); + testOutputProcedureBinaryInorderString( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + "(?,?,?,?,?)}"); } @Test public void testOutputProcedureDate() throws SQLException { createOutputProcedureDate(); - testOutputProcedureDateInorder("{call " + outputProcedureDate + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); - testOutputProcedureDateInorderObject("{call " + outputProcedureDate + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureDateInorder("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate) + + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); + testOutputProcedureDateInorderObject("{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate) + + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); } @Test public void testMixedProcedureDateScale() throws SQLException { createMixedProcedureDateScale(); - testMixedProcedureDateScaleInorder("{call " + MixedProcedureDateScale + "(?,?,?,?,?,?)}"); - testMixedProcedureDateScaleWithParameterName("{call " + MixedProcedureDateScale + "(?,?,?,?,?,?)}"); + testMixedProcedureDateScaleInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale) + "(?,?,?,?,?,?)}"); + testMixedProcedureDateScaleWithParameterName( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale) + "(?,?,?,?,?,?)}"); } @Test public void testOutputProcedureBatch() throws SQLException { createOutputProcedureBatch(); - testOutputProcedureBatchInorder("{call " + outputProcedureBatch + "(?,?,?,?)}"); + testOutputProcedureBatchInorder( + "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch) + "(?,?,?,?)}"); } @Test @@ -243,32 +280,50 @@ public void testOutputProcedure4() throws SQLException { createOutputProcedure4(); } - private static void dropTables() throws SQLException { - TestUtils.dropTableIfExists(table1, stmt); - - TestUtils.dropTableIfExists(table2, stmt); - - TestUtils.dropTableIfExists(table3, stmt); - - TestUtils.dropTableIfExists(table4, stmt); - - TestUtils.dropTableIfExists(charTable, stmt); - - TestUtils.dropTableIfExists(numericTable, stmt); - - TestUtils.dropTableIfExists(binaryTable, stmt); - - TestUtils.dropTableIfExists(dateTable, stmt); - - TestUtils.dropTableIfExists(table5, stmt); - - TestUtils.dropTableIfExists(table6, stmt); + private static void dropProcedures() throws SQLException { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProcedure2), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure2), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure3), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedure4), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureChar), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureDate), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inoutProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedure), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedure2), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedure3), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale), + stmt); + } + } - TestUtils.dropTableIfExists(scaleDateTable, stmt); + private static void dropTables() throws SQLException { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table3), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table4), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(binaryTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table5), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table6), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(scaleDateTable), stmt); + } } private static void createTables() throws SQLException { - String sql = "create table " + table1 + " (" + "PlainChar char(20) null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table1) + " (" + "PlainChar char(20) null," + "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -280,13 +335,14 @@ private static void createTables() throws SQLException { + "DeterministicVarchar varchar(50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL" + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table2 + " (" + "PlainChar char(20) null," + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table2) + " (" + "PlainChar char(20) null," + "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -300,13 +356,14 @@ private static void createTables() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table3 + " (" + "PlainBit bit null," + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table3) + " (" + "PlainBit bit null," + "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -410,25 +467,27 @@ private static void createTables() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table4 + " (" + "PlainInt int null," + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table4) + " (" + "PlainInt int null," + "RandomizedInt int ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicInt int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table5 + " (" + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table5) + " (" + "c1 int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "c2 smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -436,13 +495,14 @@ private static void createTables() throws SQLException { + "c3 bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); } - sql = "create table " + table6 + " (" + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(table6) + " (" + "c1 int ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "c2 smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -450,7 +510,8 @@ private static void createTables() throws SQLException { + "c3 bigint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); } catch (SQLException e) { fail(e.toString()); @@ -458,10 +519,12 @@ private static void createTables() throws SQLException { } private static void populateTable4() throws SQLException { - String sql = "insert into " + table4 + " values( " + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(table4) + " values( " + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -473,12 +536,14 @@ private static void populateTable4() throws SQLException { } private static void populateTable3() throws SQLException { - String sql = "insert into " + table3 + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(table3) + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // bit for (int i = 1; i <= 3; i++) { @@ -579,51 +644,60 @@ private static void populateTable3() throws SQLException { } private void createMultiInsertionSelection() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + multiStatementsProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + multiStatementsProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(multiStatementsProcedure) + + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure); - sql = "CREATE PROCEDURE " + multiStatementsProcedure - + " (@p0 char(20) = null, @p1 char(20) = null, @p2 char(20) = null, " - + "@p3 varchar(50) = null, @p4 varchar(50) = null, @p5 varchar(50) = null)" + " AS" + " INSERT INTO " - + table1 + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + " INSERT INTO " + table2 - + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + " SELECT * FROM " + table1 + " SELECT * FROM " + table2; - stmt.execute(sql); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure) + + " (@p0 char(20) = null, @p1 char(20) = null, @p2 char(20) = null, " + + "@p3 varchar(50) = null, @p4 varchar(50) = null, @p5 varchar(50) = null)" + " AS" + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(table1) + + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + " INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(table2) + " values (@p0,@p1,@p2,@p3,@p4,@p5)" + + " SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(table1) + " SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(table2); + stmt.execute(sql); + } } private void MultiInsertionSelection() throws SQLException { - try { - String sql = "{call " + multiStatementsProcedure + " (?,?,?,?,?,?)}"; - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils - .getCallableStmt(con, sql, stmtColEncSetting)) { + String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(multiStatementsProcedure) + " (?,?,?,?,?,?)}"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { - // char, varchar - for (int i = 1; i <= 3; i++) { - callableStatement.setString(i, charValues[0]); - } + // char, varchar + for (int i = 1; i <= 3; i++) { + callableStatement.setString(i, charValues[0]); + } - for (int i = 4; i <= 6; i++) { - callableStatement.setString(i, charValues[1]); - } + for (int i = 4; i <= 6; i++) { + callableStatement.setString(i, charValues[1]); + } - boolean results = callableStatement.execute(); + boolean results = callableStatement.execute(); - // skip update count which is given by insertion - while (false == results && (-1) != callableStatement.getUpdateCount()) { - results = callableStatement.getMoreResults(); - } + // skip update count which is given by insertion + while (false == results && (-1) != callableStatement.getUpdateCount()) { + results = callableStatement.getMoreResults(); + } - while (results) { - try (ResultSet rs = callableStatement.getResultSet()) { - int numberOfColumns = rs.getMetaData().getColumnCount(); + while (results) { + try (ResultSet rs = callableStatement.getResultSet()) { + int numberOfColumns = rs.getMetaData().getColumnCount(); - while (rs.next()) { - testGetString(rs, numberOfColumns); - } + while (rs.next()) { + testGetString(rs, numberOfColumns); } - results = callableStatement.getMoreResults(); } + results = callableStatement.getMoreResults(); } } catch (SQLException e) { fail(e.toString()); @@ -645,28 +719,36 @@ private void testGetString(ResultSet rs, int numberOfColumns) throws SQLExceptio } private void createInputProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + inputProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + inputProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(inputProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure); - sql = "CREATE PROCEDURE " + inputProcedure + " @p0 int, @p1 decimal(18, 0), " - + "@p2 float, @p3 real, @p4 numeric(18, 0), @p5 smallmoney, @p6 money," - + "@p7 bit, @p8 smallint, @p9 bigint, @p10 float(30), @p11 decimal(10,5), @p12 numeric(8,2), " - + "@p13 decimal(28,4), @p14 numeric(28,4) " + " AS" + " SELECT top 1 RandomizedInt FROM " - + numericTable + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p1 and " - + " DeterministicFloatDefault=@p2 and DeterministicReal=@p3 and DeterministicNumericDefault=@p4 and" - + " DeterministicSmallMoney=@p5 and DeterministicMoney=@p6 and DeterministicBit=@p7 and" - + " DeterministicSmallint=@p8 and DeterministicBigint=@p9 and DeterministicFloat=@p10 and" - + " DeterministicDecimal=@p11 and DeterministicNumeric=@p12 and DeterministicDecimal2=@p13 and" - + " DeterministicNumeric2=@p14 "; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure) + + " @p0 int, @p1 decimal(18, 0), " + + "@p2 float, @p3 real, @p4 numeric(18, 0), @p5 smallmoney, @p6 money," + + "@p7 bit, @p8 smallint, @p9 bigint, @p10 float(30), @p11 decimal(10,5), @p12 numeric(8,2), " + + "@p13 decimal(28,4), @p14 numeric(28,4) " + " AS" + " SELECT top 1 RandomizedInt FROM " + + AbstractSQLGenerator.escapeIdentifier(numericTable) + + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p1 and " + + " DeterministicFloatDefault=@p2 and DeterministicReal=@p3 and DeterministicNumericDefault=@p4 and" + + " DeterministicSmallMoney=@p5 and DeterministicMoney=@p6 and DeterministicBit=@p7 and" + + " DeterministicSmallint=@p8 and DeterministicBigint=@p9 and DeterministicFloat=@p10 and" + + " DeterministicDecimal=@p11 and DeterministicNumeric=@p12 and DeterministicDecimal2=@p13 and" + + " DeterministicNumeric2=@p14 "; - stmt.execute(sql); + stmt.execute(sql); + } } private void testInputProcedure(String sql, String[] values) throws SQLException { - - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(values[3])); if (RandomData.returnZero) @@ -703,24 +785,32 @@ private void testInputProcedure(String sql, String[] values) throws SQLException } private void createInputProcedure2() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + inputProcedure2 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + inputProcedure2; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(inputProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2); - sql = "CREATE PROCEDURE " + inputProcedure2 - + " @p0 varchar(50), @p1 uniqueidentifier, @p2 varchar(max), @p3 nchar(30), @p4 nvarchar(60), @p5 nvarchar(max), " - + " @p6 varchar(8000), @p7 nvarchar(4000)" + " AS" - + " SELECT top 1 RandomizedVarchar, DeterministicUniqueidentifier, DeterministicVarcharMax, RandomizedNchar, " - + " DeterministicNvarchar, DeterministicNvarcharMax, DeterministicVarchar8000, RandomizedNvarchar4000 FROM " - + charTable + " where DeterministicVarchar = @p0 and DeterministicUniqueidentifier =@p1"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProcedure2) + + " @p0 varchar(50), @p1 uniqueidentifier, @p2 varchar(max), @p3 nchar(30), @p4 nvarchar(60), @p5 nvarchar(max), " + + " @p6 varchar(8000), @p7 nvarchar(4000)" + " AS" + + " SELECT top 1 RandomizedVarchar, DeterministicUniqueidentifier, DeterministicVarcharMax, RandomizedNchar, " + + " DeterministicNvarchar, DeterministicNvarcharMax, DeterministicVarchar8000, RandomizedNvarchar4000 FROM " + + AbstractSQLGenerator.escapeIdentifier(charTable) + + " where DeterministicVarchar = @p0 and DeterministicUniqueidentifier =@p1"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testInputProcedure2(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setString(1, charValues[1]); callableStatement.setUniqueIdentifier(2, charValues[6]); @@ -749,21 +839,29 @@ private void testInputProcedure2(String sql) throws SQLException { } private void createOutputProcedure3() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure3 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure3; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure3) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3); - sql = "CREATE PROCEDURE " + outputProcedure3 + " @p0 int OUTPUT, @p1 int OUTPUT " + " AS" - + " SELECT top 1 @p0=DeterministicInt FROM " + table3 + " SELECT top 1 @p1=RandomizedInt FROM " - + table4; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure3) + + " @p0 int OUTPUT, @p1 int OUTPUT " + " AS" + " SELECT top 1 @p0=DeterministicInt FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " SELECT top 1 @p1=RandomizedInt FROM " + + AbstractSQLGenerator.escapeIdentifier(table4); + + stmt.execute(sql); + } } private void testOutputProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -791,8 +889,10 @@ private void testOutputProcedure3RandomOrder(String sql) throws SQLException { private void testOutputProcedure3Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -811,8 +911,10 @@ private void testOutputProcedure3Inorder(String sql) throws SQLException { private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -830,24 +932,31 @@ private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { } private void createOutputProcedure2() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure2 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure2; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedure2 - + " @p0 int OUTPUT, @p1 int OUTPUT, @p2 smallint OUTPUT, @p3 smallint OUTPUT, @p4 tinyint OUTPUT, @p5 tinyint OUTPUT, @p6 smallmoney OUTPUT," - + " @p7 smallmoney OUTPUT, @p8 money OUTPUT, @p9 money OUTPUT " + " AS" - + " SELECT top 1 @p0=PlainInt, @p1=DeterministicInt, @p2=PlainSmallint," - + " @p3=RandomizedSmallint, @p4=PlainTinyint, @p5=DeterministicTinyint, @p6=DeterministicSmallMoney, @p7=PlainSmallMoney," - + " @p8=PlainMoney, @p9=DeterministicMoney FROM " + table3; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure2) + + " @p0 int OUTPUT, @p1 int OUTPUT, @p2 smallint OUTPUT, @p3 smallint OUTPUT, @p4 tinyint OUTPUT, @p5 tinyint OUTPUT, @p6 smallmoney OUTPUT," + + " @p7 smallmoney OUTPUT, @p8 money OUTPUT, @p9 money OUTPUT " + " AS" + + " SELECT top 1 @p0=PlainInt, @p1=DeterministicInt, @p2=PlainSmallint," + + " @p3=RandomizedSmallint, @p4=PlainTinyint, @p5=DeterministicTinyint, @p6=DeterministicSmallMoney, @p7=PlainSmallMoney," + + " @p8=PlainMoney, @p9=DeterministicMoney FROM " + AbstractSQLGenerator.escapeIdentifier(table3); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedure2RandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -898,8 +1007,10 @@ private void testOutputProcedure2RandomOrder(String sql, String[] values) throws private void testOutputProcedure2Inorder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -950,8 +1061,10 @@ private void testOutputProcedure2Inorder(String sql, String[] values) throws SQL private void testOutputProcedure2ReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -1001,23 +1114,31 @@ private void testOutputProcedure2ReverseOrder(String sql, String[] values) throw } private void createOutputProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedure + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, " - + "@p3 bigint OUTPUT, @p4 tinyint OUTPUT, @p5 smallmoney OUTPUT, @p6 money OUTPUT " + " AS" - + " SELECT top 1 @p0=RandomizedInt, @p1=DeterministicFloatDefault, @p2=RandomizedSmallint," - + " @p3=RandomizedBigint, @p4=DeterministicTinyint, @p5=DeterministicSmallMoney, @p6=DeterministicMoney FROM " - + table3; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, " + + "@p3 bigint OUTPUT, @p4 tinyint OUTPUT, @p5 smallmoney OUTPUT, @p6 money OUTPUT " + " AS" + + " SELECT top 1 @p0=RandomizedInt, @p1=DeterministicFloatDefault, @p2=RandomizedSmallint," + + " @p3=RandomizedBigint, @p4=DeterministicTinyint, @p5=DeterministicSmallMoney, @p6=DeterministicMoney FROM " + + AbstractSQLGenerator.escapeIdentifier(table3); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureRandomOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1064,8 +1185,10 @@ private void testOutputProcedureRandomOrder(String sql, String[] values) throws private void testOutputProcedureInorder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1105,8 +1228,10 @@ private void testOutputProcedureInorder(String sql, String[] values) throws SQLE private void testOutputProcedureReverseOrder(String sql, String[] values) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1144,20 +1269,28 @@ private void testOutputProcedureReverseOrder(String sql, String[] values) throws } private void createInOutProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + inoutProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + inoutProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(inoutProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure); - sql = "CREATE PROCEDURE " + inoutProcedure + " @p0 int OUTPUT" + " AS" - + " SELECT top 1 @p0=DeterministicInt FROM " + table3 + " where DeterministicInt=@p0"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inoutProcedure) + " @p0 int OUTPUT" + + " AS" + " SELECT top 1 @p0=DeterministicInt FROM " + AbstractSQLGenerator.escapeIdentifier(table3) + + " where DeterministicInt=@p0"; + + stmt.execute(sql); + } } private void testInOutProcedure(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(numericValues[3])); callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1172,21 +1305,30 @@ private void testInOutProcedure(String sql) throws SQLException { } private void createMixedProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedure - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + mixedProcedure; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedure) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + mixedProcedure + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 decimal " + " AS" - + " SELECT top 1 @p0=DeterministicInt2, @p1=RandomizedFloatDefault FROM " + table3 - + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p3" + " return 123"; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 decimal " + " AS" + + " SELECT top 1 @p0=DeterministicInt2, @p1=RandomizedFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + + " where DeterministicInt=@p0 and DeterministicDecimalDefault=@p3" + " return 123"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedure(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.setInt(2, Integer.parseInt(numericValues[3])); @@ -1212,21 +1354,30 @@ private void testMixedProcedure(String sql) throws SQLException { } private void createMixedProcedure2() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedure2 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + mixedProcedure2; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedure2) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2); - sql = "CREATE PROCEDURE " + mixedProcedure2 + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 int, @p4 float " + " AS" - + " SELECT top 1 @p0=DeterministicInt, @p1=PlainFloatDefault FROM " + table3 - + " where PlainInt=@p3 and DeterministicFloatDefault=@p4"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure2) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p3 int, @p4 float " + " AS" + + " SELECT top 1 @p0=DeterministicInt, @p1=PlainFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + + " where PlainInt=@p3 and DeterministicFloatDefault=@p4"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedure2RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1259,8 +1410,10 @@ private void testMixedProcedure2RandomOrder(String sql) throws SQLException { private void testMixedProcedure2Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1279,22 +1432,29 @@ private void testMixedProcedure2Inorder(String sql) throws SQLException { } private void createMixedProcedure3() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedure3 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + mixedProcedure3; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedure3) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3); - sql = "CREATE PROCEDURE " + mixedProcedure3 - + " @p0 bigint OUTPUT, @p1 float OUTPUT, @p2 int OUTPUT, @p3 smallint" + " AS" - + " SELECT top 1 @p0=PlainBigint, @p1=PlainFloatDefault FROM " + table3 - + " where PlainInt=@p2 and PlainSmallint=@p3"; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedure3) + + " @p0 bigint OUTPUT, @p1 float OUTPUT, @p2 int OUTPUT, @p3 smallint" + " AS" + + " SELECT top 1 @p0=PlainBigint, @p1=PlainFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " where PlainInt=@p2 and PlainSmallint=@p3"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedure3RandomOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1327,8 +1487,10 @@ private void testMixedProcedure3RandomOrder(String sql) throws SQLException { private void testMixedProcedure3Inorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1348,8 +1510,10 @@ private void testMixedProcedure3Inorder(String sql) throws SQLException { private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1368,24 +1532,32 @@ private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { } private void createMixedProcedureNumericPrcisionScale() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + mixedProcedureNumericPrcisionScale + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(mixedProcedureNumericPrcisionScale) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " - + mixedProcedureNumericPrcisionScale; - stmt.execute(sql); + + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + mixedProcedureNumericPrcisionScale - + " @p1 decimal(18,0) OUTPUT, @p2 decimal(10,5) OUTPUT, @p3 numeric(18, 0) OUTPUT, @p4 numeric(8,2) OUTPUT " - + " AS" + " SELECT top 1 @p1=RandomizedDecimalDefault, @p2=DeterministicDecimal," - + " @p3=RandomizedNumericDefault, @p4=DeterministicNumeric FROM " + table3 - + " where DeterministicDecimal=@p2 and DeterministicNumeric=@p4" + " return 123"; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(mixedProcedureNumericPrcisionScale) + + " @p1 decimal(18,0) OUTPUT, @p2 decimal(10,5) OUTPUT, @p3 numeric(18, 0) OUTPUT, @p4 numeric(8,2) OUTPUT " + + " AS" + " SELECT top 1 @p1=RandomizedDecimalDefault, @p2=DeterministicDecimal," + + " @p3=RandomizedNumericDefault, @p4=DeterministicNumeric FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + + " where DeterministicDecimal=@p2 and DeterministicNumeric=@p4" + " return 123"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter(2, java.sql.Types.DECIMAL, 10, 5); @@ -1414,8 +1586,10 @@ private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter("p1", java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter("p2", java.sql.Types.DECIMAL, 10, 5); @@ -1443,25 +1617,33 @@ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) thr } private void createOutputProcedureChar() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureChar - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureChar; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureChar) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedureChar - + " @p0 char(20) OUTPUT,@p1 varchar(50) OUTPUT,@p2 nchar(30) OUTPUT," - + "@p3 nvarchar(60) OUTPUT, @p4 uniqueidentifier OUTPUT, @p5 varchar(max) OUTPUT, @p6 nvarchar(max) OUTPUT, @p7 varchar(8000) OUTPUT, @p8 nvarchar(4000) OUTPUT" - + " AS" + " SELECT top 1 @p0=DeterministicChar,@p1=RandomizedVarChar,@p2=RandomizedNChar," - + " @p3=DeterministicNVarChar, @p4=DeterministicUniqueidentifier, @p5=DeterministicVarcharMax," - + " @p6=DeterministicNvarcharMax, @p7=DeterministicVarchar8000, @p8=RandomizedNvarchar4000 FROM " - + charTable; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureChar) + + " @p0 char(20) OUTPUT,@p1 varchar(50) OUTPUT,@p2 nchar(30) OUTPUT," + + "@p3 nvarchar(60) OUTPUT, @p4 uniqueidentifier OUTPUT, @p5 varchar(max) OUTPUT, @p6 nvarchar(max) OUTPUT, @p7 varchar(8000) OUTPUT, @p8 nvarchar(4000) OUTPUT" + + " AS" + " SELECT top 1 @p0=DeterministicChar,@p1=RandomizedVarChar,@p2=RandomizedNChar," + + " @p3=DeterministicNVarChar, @p4=DeterministicUniqueidentifier, @p5=DeterministicVarcharMax," + + " @p6=DeterministicNvarcharMax, @p7=DeterministicVarchar8000, @p8=RandomizedNvarchar4000 FROM " + + AbstractSQLGenerator.escapeIdentifier(charTable); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureCharInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1508,8 +1690,11 @@ private void testOutputProcedureCharInorder(String sql) throws SQLException { private void testOutputProcedureCharInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1558,27 +1743,37 @@ private void testOutputProcedureCharInorderObject(String sql) throws SQLExceptio } private void createOutputProcedureNumeric() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureNumeric - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureNumeric; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureNumeric) + + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric); - sql = "CREATE PROCEDURE " + outputProcedureNumeric - + " @p0 bit OUTPUT, @p1 tinyint OUTPUT, @p2 smallint OUTPUT, @p3 int OUTPUT," - + " @p4 bigint OUTPUT, @p5 float OUTPUT, @p6 float(30) output, @p7 real output, @p8 decimal(18, 0) output, @p9 decimal(10,5) output," - + " @p10 numeric(18, 0) output, @p11 numeric(8,2) output, @p12 smallmoney output, @p13 money output, @p14 decimal(28,4) output, @p15 numeric(28,4) output" - + " AS" + " SELECT top 1 @p0=DeterministicBit, @p1=RandomizedTinyint, @p2=DeterministicSmallint," - + " @p3=RandomizedInt, @p4=DeterministicBigint, @p5=RandomizedFloatDefault, @p6=DeterministicFloat," - + " @p7=RandomizedReal, @p8=DeterministicDecimalDefault, @p9=RandomizedDecimal," - + " @p10=DeterministicNumericDefault, @p11=RandomizedNumeric, @p12=RandomizedSmallMoney, @p13=DeterministicMoney," - + " @p14=DeterministicDecimal2, @p15=DeterministicNumeric2 FROM " + numericTable; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); + + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNumeric) + + " @p0 bit OUTPUT, @p1 tinyint OUTPUT, @p2 smallint OUTPUT, @p3 int OUTPUT," + + " @p4 bigint OUTPUT, @p5 float OUTPUT, @p6 float(30) output, @p7 real output, @p8 decimal(18, 0) output, @p9 decimal(10,5) output," + + " @p10 numeric(18, 0) output, @p11 numeric(8,2) output, @p12 smallmoney output, @p13 money output, @p14 decimal(28,4) output, @p15 numeric(28,4) output" + + " AS" + " SELECT top 1 @p0=DeterministicBit, @p1=RandomizedTinyint, @p2=DeterministicSmallint," + + " @p3=RandomizedInt, @p4=DeterministicBigint, @p5=RandomizedFloatDefault, @p6=DeterministicFloat," + + " @p7=RandomizedReal, @p8=DeterministicDecimalDefault, @p9=RandomizedDecimal," + + " @p10=DeterministicNumericDefault, @p11=RandomizedNumeric, @p12=RandomizedSmallMoney, @p13=DeterministicMoney," + + " @p14=DeterministicDecimal2, @p15=DeterministicNumeric2 FROM " + + AbstractSQLGenerator.escapeIdentifier(numericTable); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.BIT); callableStatement.registerOutParameter(2, java.sql.Types.TINYINT); callableStatement.registerOutParameter(3, java.sql.Types.SMALLINT); @@ -1664,8 +1859,11 @@ private void testOutputProcedureNumericInorder(String sql) throws SQLException { private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.BIT); callableStatement.registerOutParameter(2, java.sql.Types.TINYINT); callableStatement.registerOutParameter(3, java.sql.Types.SMALLINT); @@ -1944,23 +2142,32 @@ private Object getxxx(int ordinal, Class coercion, } private void createOutputProcedureBinary() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureBinary - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureBinary; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureBinary) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary); - sql = "CREATE PROCEDURE " + outputProcedureBinary - + " @p0 binary(20) OUTPUT,@p1 varbinary(50) OUTPUT,@p2 varbinary(max) OUTPUT," - + " @p3 binary(512) OUTPUT,@p4 varbinary(8000) OUTPUT " + " AS" - + " SELECT top 1 @p0=RandomizedBinary,@p1=DeterministicVarbinary,@p2=DeterministicVarbinaryMax," - + " @p3=DeterministicBinary512,@p4=DeterministicBinary8000 FROM " + binaryTable; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - stmt.execute(sql); + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBinary) + + " @p0 binary(20) OUTPUT,@p1 varbinary(50) OUTPUT,@p2 varbinary(max) OUTPUT," + + " @p3 binary(512) OUTPUT,@p4 varbinary(8000) OUTPUT " + " AS" + + " SELECT top 1 @p0=RandomizedBinary,@p1=DeterministicVarbinary,@p2=DeterministicVarbinaryMax," + + " @p3=DeterministicBinary512,@p4=DeterministicBinary8000 FROM " + + AbstractSQLGenerator.escapeIdentifier(binaryTable); + + stmt.execute(sql); + } } private void testOutputProcedureBinaryInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.BINARY, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARBINARY, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.LONGVARBINARY); @@ -2005,8 +2212,11 @@ private void testOutputProcedureBinaryInorder(String sql) throws SQLException { private void testOutputProcedureBinaryInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.BINARY, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARBINARY, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.LONGVARBINARY); @@ -2044,8 +2254,11 @@ private void testOutputProcedureBinaryInorderObject(String sql) throws SQLExcept private void testOutputProcedureBinaryInorderString(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.BINARY, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARBINARY, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.LONGVARBINARY); @@ -2081,7 +2294,7 @@ private void testOutputProcedureBinaryInorderString(String sql) throws SQLExcept } protected static void createDateTableCallableStatement() throws SQLException { - String sql = "create table " + dateTable + " (" + "PlainDate date null," + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + "PlainDate date null," + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + cekName + ") NULL," + "DeterministicDate date ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " @@ -2137,7 +2350,8 @@ protected static void createDateTableCallableStatement() throws SQLException { + ");"; - try { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { stmt.execute(sql); stmt.execute("DBCC FREEPROCCACHE"); } catch (SQLException e) { @@ -2173,83 +2387,95 @@ private static LinkedList createTemporalTypesCallableStatement(boolean n } private static void populateDateNormalCase() throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { - // date - for (int i = 1; i <= 3; i++) { - sqlPstmt.setDate(i, (Date) dateValues.get(0)); - } + // date + for (int i = 1; i <= 3; i++) { + sqlPstmt.setDate(i, (Date) dateValues.get(0)); + } - // datetime2 default - for (int i = 4; i <= 6; i++) { - sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); - } + // datetime2 default + for (int i = 4; i <= 6; i++) { + sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); + } - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); - } + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); + } - // time default - for (int i = 10; i <= 12; i++) { - sqlPstmt.setTime(i, (Time) dateValues.get(3)); - } + // time default + for (int i = 10; i <= 12; i++) { + sqlPstmt.setTime(i, (Time) dateValues.get(3)); + } - // datetime2(2) - for (int i = 13; i <= 15; i++) { - sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); - } + // datetime2(2) + for (int i = 13; i <= 15; i++) { + sqlPstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); + } - // time(2) - for (int i = 16; i <= 18; i++) { - sqlPstmt.setTime(i, (Time) dateValues.get(5), 2); - } + // time(2) + for (int i = 16; i <= 18; i++) { + sqlPstmt.setTime(i, (Time) dateValues.get(5), 2); + } - // datetimeoffset(2) - for (int i = 19; i <= 21; i++) { - sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); - } + // datetimeoffset(2) + for (int i = 19; i <= 21; i++) { + sqlPstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); + } - // datetime() - for (int i = 22; i <= 24; i++) { - sqlPstmt.setDateTime(i, (Timestamp) dateValues.get(7)); - } + // datetime() + for (int i = 22; i <= 24; i++) { + sqlPstmt.setDateTime(i, (Timestamp) dateValues.get(7)); + } - // smalldatetime() - for (int i = 25; i <= 27; i++) { - sqlPstmt.setSmallDateTime(i, (Timestamp) dateValues.get(8)); + // smalldatetime() + for (int i = 25; i <= 27; i++) { + sqlPstmt.setSmallDateTime(i, (Timestamp) dateValues.get(8)); + } + sqlPstmt.execute(); } - sqlPstmt.execute(); } private void createOutputProcedureDate() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureDate - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureDate; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureDate) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + outputProcedureDate - + " @p0 date OUTPUT, @p01 date OUTPUT, @p1 datetime2 OUTPUT, @p11 datetime2 OUTPUT," - + " @p2 datetimeoffset OUTPUT, @p21 datetimeoffset OUTPUT, @p3 time OUTPUT, @p31 time OUTPUT, @p4 datetime OUTPUT, @p41 datetime OUTPUT," - + " @p5 smalldatetime OUTPUT, @p51 smalldatetime OUTPUT, @p6 datetime2(2) OUTPUT, @p61 datetime2(2) OUTPUT, @p7 time(2) OUTPUT, @p71 time(2) OUTPUT, " - + " @p8 datetimeoffset(2) OUTPUT, @p81 datetimeoffset(2) OUTPUT " + " AS" - + " SELECT top 1 @p0=PlainDate,@p01=RandomizedDate,@p1=PlainDatetime2Default,@p11=RandomizedDatetime2Default," - + " @p2=PlainDatetimeoffsetDefault,@p21=DeterministicDatetimeoffsetDefault," - + " @p3=PlainTimeDefault,@p31=DeterministicTimeDefault," - + " @p4=PlainDateTime,@p41=DeterministicDateTime, @p5=PlainSmallDateTime,@p51=RandomizedSmallDateTime, " - + " @p6=PlainDatetime2,@p61=RandomizedDatetime2, @p7=PlainTime,@p71=Deterministictime, " - + " @p8=PlainDatetimeoffset, @p81=RandomizedDatetimeoffset" + " FROM " + dateTable; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDate) + + " @p0 date OUTPUT, @p01 date OUTPUT, @p1 datetime2 OUTPUT, @p11 datetime2 OUTPUT," + + " @p2 datetimeoffset OUTPUT, @p21 datetimeoffset OUTPUT, @p3 time OUTPUT, @p31 time OUTPUT, @p4 datetime OUTPUT, @p41 datetime OUTPUT," + + " @p5 smalldatetime OUTPUT, @p51 smalldatetime OUTPUT, @p6 datetime2(2) OUTPUT, @p61 datetime2(2) OUTPUT, @p7 time(2) OUTPUT, @p71 time(2) OUTPUT, " + + " @p8 datetimeoffset(2) OUTPUT, @p81 datetimeoffset(2) OUTPUT " + " AS" + + " SELECT top 1 @p0=PlainDate,@p01=RandomizedDate,@p1=PlainDatetime2Default,@p11=RandomizedDatetime2Default," + + " @p2=PlainDatetimeoffsetDefault,@p21=DeterministicDatetimeoffsetDefault," + + " @p3=PlainTimeDefault,@p31=DeterministicTimeDefault," + + " @p4=PlainDateTime,@p41=DeterministicDateTime, @p5=PlainSmallDateTime,@p51=RandomizedSmallDateTime, " + + " @p6=PlainDatetime2,@p61=RandomizedDatetime2, @p7=PlainTime,@p71=Deterministictime, " + + " @p8=PlainDatetimeoffset, @p81=RandomizedDatetimeoffset" + " FROM " + + AbstractSQLGenerator.escapeIdentifier(dateTable); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureDateInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2300,8 +2526,11 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { private void testOutputProcedureDateInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2351,25 +2580,34 @@ private void testOutputProcedureDateInorderObject(String sql) throws SQLExceptio } private void createOutputProcedureBatch() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedureBatch - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedureBatch; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureBatch) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - // If a procedure contains more than one SQL statement, it is considered - // to be a batch of SQL statements. - sql = "CREATE PROCEDURE " + outputProcedureBatch - + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, @p3 smallmoney OUTPUT " + " AS" - + " select top 1 @p0=RandomizedInt FROM " + table3 + " select top 1 @p1=DeterministicFloatDefault FROM " - + table3 + " select top 1 @p2=RandomizedSmallint FROM " + table3 - + " select top 1 @p3=DeterministicSmallMoney FROM " + table3; + // If a procedure contains more than one SQL statement, it is considered + // to be a batch of SQL statements. + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureBatch) + + " @p0 int OUTPUT, @p1 float OUTPUT, @p2 smallint OUTPUT, @p3 smallmoney OUTPUT " + " AS" + + " select top 1 @p0=RandomizedInt FROM " + AbstractSQLGenerator.escapeIdentifier(table3) + + " select top 1 @p1=DeterministicFloatDefault FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " select top 1 @p2=RandomizedSmallint FROM " + + AbstractSQLGenerator.escapeIdentifier(table3) + " select top 1 @p3=DeterministicSmallMoney FROM " + + AbstractSQLGenerator.escapeIdentifier(table3); - stmt.execute(sql); + stmt.execute(sql); + } } private void testOutputProcedureBatchInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -2394,39 +2632,57 @@ private void testOutputProcedureBatchInorder(String sql) throws SQLException { } private void createOutputProcedure4() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure4 - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure4; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedure4) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedure4); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "create procedure " + outputProcedure4 - + " @in1 int, @in2 smallint, @in3 bigint, @in4 int, @in5 smallint, @in6 bigint, @out1 int output, @out2 smallint output, @out3 bigint output, @out4 int output, @out5 smallint output, @out6 bigint output" - + " as " + " insert into " + table5 + " values (@in1, @in2, @in3)" + " insert into " + table6 - + " values (@in4, @in5, @in6)" + " select * from " + table5 + " select * from " + table6 - + " select @out1 = c1, @out2=c2, @out3=c3 from " + table5 - + " select @out4 = c1, @out5=c2, @out6=c3 from " + table6; + sql = "create procedure " + AbstractSQLGenerator.escapeIdentifier(outputProcedure4) + + " @in1 int, @in2 smallint, @in3 bigint, @in4 int, @in5 smallint, @in6 bigint, @out1 int output, @out2 smallint output, @out3 bigint output, @out4 int output, @out5 smallint output, @out6 bigint output" + + " as " + " insert into " + AbstractSQLGenerator.escapeIdentifier(table5) + + " values (@in1, @in2, @in3)" + " insert into " + AbstractSQLGenerator.escapeIdentifier(table6) + + " values (@in4, @in5, @in6)" + " select * from " + AbstractSQLGenerator.escapeIdentifier(table5) + + " select * from " + AbstractSQLGenerator.escapeIdentifier(table6) + + " select @out1 = c1, @out2=c2, @out3=c3 from " + AbstractSQLGenerator.escapeIdentifier(table5) + + " select @out4 = c1, @out5=c2, @out6=c3 from " + AbstractSQLGenerator.escapeIdentifier(table6); - stmt.execute(sql); + stmt.execute(sql); + } } private void createMixedProcedureDateScale() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + MixedProcedureDateScale - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + MixedProcedureDateScale; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(outputProcedureDateScale) + + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + stmt.execute(sql); - sql = "CREATE PROCEDURE " + MixedProcedureDateScale + " @p1 datetime2(2) OUTPUT, @p2 datetime2(2) OUTPUT," - + " @p3 time(2) OUTPUT, @p4 time(2) OUTPUT, @p5 datetimeoffset(2) OUTPUT, @p6 datetimeoffset(2) OUTPUT " - + " AS" - + " SELECT top 1 @p1=DeterministicDatetime2,@p2=RandomizedDatetime2,@p3=DeterministicTime,@p4=RandomizedTime," - + " @p5=DeterministicDatetimeoffset,@p6=RandomizedDatetimeoffset " + " FROM " + scaleDateTable - + " where DeterministicDatetime2 = @p1 and DeterministicTime = @p3 and DeterministicDatetimeoffset=@p5"; + sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureDateScale) + + " @p1 datetime2(2) OUTPUT, @p2 datetime2(2) OUTPUT," + + " @p3 time(2) OUTPUT, @p4 time(2) OUTPUT, @p5 datetimeoffset(2) OUTPUT, @p6 datetimeoffset(2) OUTPUT " + + " AS" + + " SELECT top 1 @p1=DeterministicDatetime2,@p2=RandomizedDatetime2,@p3=DeterministicTime,@p4=RandomizedTime," + + " @p5=DeterministicDatetimeoffset,@p6=RandomizedDatetimeoffset " + " FROM " + + AbstractSQLGenerator.escapeIdentifier(scaleDateTable) + + " where DeterministicDatetime2 = @p1 and DeterministicTime = @p3 and DeterministicDatetimeoffset=@p5"; - stmt.execute(sql); + stmt.execute(sql); + } } private void testMixedProcedureDateScaleInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter(1, java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter(2, java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter(3, java.sql.Types.TIME, 2); @@ -2454,8 +2710,11 @@ private void testMixedProcedureDateScaleInorder(String sql) throws SQLException private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils.getCallableStmt(con, - sql, stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) TestUtils + .getCallableStmt(con, sql, stmtColEncSetting)) { + callableStatement.registerOutParameter("p1", java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter("p2", java.sql.Types.TIMESTAMP, 2); callableStatement.registerOutParameter("p3", java.sql.Types.TIME, 2); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java index 0448f3fff9..c7d1cd3f5d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -18,11 +19,13 @@ import org.opentest4j.TestAbortedException; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; /** @@ -51,12 +54,15 @@ public class JDBCEncryptionDecryptionTest extends AESetup { */ @Test public void testCharSpecificSetter() throws SQLException { - charValues = createCharValues(nullable); - dropTables(stmt); - createCharTable(); - populateCharNormalCase(charValues); - testChar(stmt, charValues); - testChar(null, charValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + charValues = createCharValues(nullable); + dropTables(stmt); + createCharTable(); + populateCharNormalCase(charValues); + testChar(stmt, charValues); + testChar(null, charValues); + } } /** @@ -66,12 +72,15 @@ public void testCharSpecificSetter() throws SQLException { */ @Test public void testCharSetObject() throws SQLException { - charValues = createCharValues(nullable); - dropTables(stmt); - createCharTable(); - populateCharSetObject(charValues); - testChar(stmt, charValues); - testChar(null, charValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + charValues = createCharValues(nullable); + dropTables(stmt); + createCharTable(); + populateCharSetObject(charValues); + testChar(stmt, charValues); + testChar(null, charValues); + } } /** @@ -81,14 +90,16 @@ public void testCharSetObject() throws SQLException { */ @Test public void testCharSetObjectWithJDBCTypes() throws SQLException { - skipTestForJava7(); - - charValues = createCharValues(nullable); - dropTables(stmt); - createCharTable(); - populateCharSetObjectWithJDBCTypes(charValues); - testChar(stmt, charValues); - testChar(null, charValues); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + charValues = createCharValues(nullable); + dropTables(stmt); + createCharTable(); + populateCharSetObjectWithJDBCTypes(charValues); + testChar(stmt, charValues); + testChar(null, charValues); + } } /** @@ -98,12 +109,15 @@ public void testCharSetObjectWithJDBCTypes() throws SQLException { */ @Test public void testCharSpecificSetterNull() throws SQLException { - String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; - dropTables(stmt); - createCharTable(); - populateCharNormalCase(charValuesNull); - testChar(stmt, charValuesNull); - testChar(null, charValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; + dropTables(stmt); + createCharTable(); + populateCharNormalCase(charValuesNull); + testChar(stmt, charValuesNull); + testChar(null, charValuesNull); + } } /** @@ -113,12 +127,15 @@ public void testCharSpecificSetterNull() throws SQLException { */ @Test public void testCharSetObjectNull() throws SQLException { - String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; - dropTables(stmt); - createCharTable(); - populateCharSetObject(charValuesNull); - testChar(stmt, charValuesNull); - testChar(null, charValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; + dropTables(stmt); + createCharTable(); + populateCharSetObject(charValuesNull); + testChar(stmt, charValuesNull); + testChar(null, charValuesNull); + } } /** @@ -128,12 +145,15 @@ public void testCharSetObjectNull() throws SQLException { */ @Test public void testCharSetNull() throws SQLException { - String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; - dropTables(stmt); - createCharTable(); - populateCharNullCase(); - testChar(stmt, charValuesNull); - testChar(null, charValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + String[] charValuesNull = {null, null, null, null, null, null, null, null, null}; + dropTables(stmt); + createCharTable(); + populateCharNullCase(); + testChar(stmt, charValuesNull); + testChar(null, charValuesNull); + } } /** @@ -143,12 +163,15 @@ public void testCharSetNull() throws SQLException { */ @Test public void testBinarySpecificSetter() throws SQLException { - LinkedList byteValues = createbinaryValues(false); - dropTables(stmt); - createBinaryTable(); - populateBinaryNormalCase(byteValues); - testBinary(stmt, byteValues); - testBinary(null, byteValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + LinkedList byteValues = createbinaryValues(false); + dropTables(stmt); + createBinaryTable(); + populateBinaryNormalCase(byteValues); + testBinary(stmt, byteValues); + testBinary(null, byteValues); + } } /** @@ -158,12 +181,15 @@ public void testBinarySpecificSetter() throws SQLException { */ @Test public void testBinarySetobject() throws SQLException { - byteValuesSetObject = createbinaryValues(false); - dropTables(stmt); - createBinaryTable(); - populateBinarySetObject(byteValuesSetObject); - testBinary(stmt, byteValuesSetObject); - testBinary(null, byteValuesSetObject); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesSetObject = createbinaryValues(false); + dropTables(stmt); + createBinaryTable(); + populateBinarySetObject(byteValuesSetObject); + testBinary(stmt, byteValuesSetObject); + testBinary(null, byteValuesSetObject); + } } /** @@ -173,12 +199,15 @@ public void testBinarySetobject() throws SQLException { */ @Test public void testBinarySetNull() throws SQLException { - byteValuesNull = createbinaryValues(true); - dropTables(stmt); - createBinaryTable(); - populateBinaryNullCase(); - testBinary(stmt, byteValuesNull); - testBinary(null, byteValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesNull = createbinaryValues(true); + dropTables(stmt); + createBinaryTable(); + populateBinaryNullCase(); + testBinary(stmt, byteValuesNull); + testBinary(null, byteValuesNull); + } } /** @@ -188,12 +217,15 @@ public void testBinarySetNull() throws SQLException { */ @Test public void testBinarySpecificSetterNull() throws SQLException { - byteValuesNull = createbinaryValues(true); - dropTables(stmt); - createBinaryTable(); - populateBinaryNormalCase(null); - testBinary(stmt, byteValuesNull); - testBinary(null, byteValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesNull = createbinaryValues(true); + dropTables(stmt); + createBinaryTable(); + populateBinaryNormalCase(null); + testBinary(stmt, byteValuesNull); + testBinary(null, byteValuesNull); + } } /** @@ -203,12 +235,15 @@ public void testBinarySpecificSetterNull() throws SQLException { */ @Test public void testBinarysetObjectNull() throws SQLException { - byteValuesNull = createbinaryValues(true); - dropTables(stmt); - createBinaryTable(); - populateBinarySetObject(null); - testBinary(stmt, byteValuesNull); - testBinary(null, byteValuesNull); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesNull = createbinaryValues(true); + dropTables(stmt); + createBinaryTable(); + populateBinarySetObject(null); + testBinary(stmt, byteValuesNull); + testBinary(null, byteValuesNull); + } } /** @@ -218,14 +253,16 @@ public void testBinarysetObjectNull() throws SQLException { */ @Test public void testBinarySetObjectWithJDBCTypes() throws SQLException { - skipTestForJava7(); - - byteValuesSetObject = createbinaryValues(false); - dropTables(stmt); - createBinaryTable(); - populateBinarySetObjectWithJDBCType(byteValuesSetObject); - testBinary(stmt, byteValuesSetObject); - testBinary(null, byteValuesSetObject); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + byteValuesSetObject = createbinaryValues(false); + dropTables(stmt); + createBinaryTable(); + populateBinarySetObjectWithJDBCType(byteValuesSetObject); + testBinary(stmt, byteValuesSetObject); + testBinary(null, byteValuesSetObject); + } } /** @@ -235,12 +272,15 @@ public void testBinarySetObjectWithJDBCTypes() throws SQLException { */ @Test public void testDateSpecificSetter() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateNormalCase(dateValues); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateNormalCase(dateValues); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -250,12 +290,15 @@ public void testDateSpecificSetter() throws SQLException { */ @Test public void testDateSetObject() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObject(dateValues, ""); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObject(dateValues, ""); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -265,12 +308,15 @@ public void testDateSetObject() throws SQLException { */ @Test public void testDateSetObjectWithJavaType() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObject(dateValues, "setwithJavaType"); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObject(dateValues, "setwithJavaType"); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -280,12 +326,15 @@ public void testDateSetObjectWithJavaType() throws SQLException { */ @Test public void testDateSetObjectWithJDBCType() throws SQLException { - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObject(dateValues, "setwithJDBCType"); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObject(dateValues, "setwithJDBCType"); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -295,13 +344,16 @@ public void testDateSetObjectWithJDBCType() throws SQLException { */ @Test public void testDateSpecificSetterMinMaxValue() throws SQLException { - RandomData.returnMinMax = true; - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateNormalCase(dateValues); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + RandomData.returnMinMax = true; + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateNormalCase(dateValues); + testDate(stmt, dateValues); + testDate(null, dateValues); + } } /** @@ -311,15 +363,18 @@ public void testDateSpecificSetterMinMaxValue() throws SQLException { */ @Test public void testDateSetNull() throws SQLException { - RandomData.returnNull = true; - nullable = true; - - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateNullCase(); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + RandomData.returnNull = true; + nullable = true; + + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateNullCase(); + testDate(stmt, dateValues); + testDate(null, dateValues); + } nullable = false; RandomData.returnNull = false; @@ -335,12 +390,15 @@ public void testDateSetObjectNull() throws SQLException { RandomData.returnNull = true; nullable = true; - dateValues = createTemporalTypes(nullable); - dropTables(stmt); - createDateTable(); - populateDateSetObjectNull(); - testDate(stmt, dateValues); - testDate(null, dateValues); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dateValues = createTemporalTypes(nullable); + dropTables(stmt); + createDateTable(); + populateDateSetObjectNull(); + testDate(stmt, dateValues); + testDate(null, dateValues); + } nullable = false; RandomData.returnNull = false; @@ -357,11 +415,14 @@ public void testNumericSpecificSetter() throws TestAbortedException, Exception { numericValues2 = new String[numericValues.length]; System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - dropTables(stmt); - createNumericTable(); - populateNumeric(numericValues); - testNumeric(stmt, numericValues, false); - testNumeric(null, numericValues2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumeric(numericValues); + testNumeric(stmt, numericValues, false); + testNumeric(null, numericValues2, false); + } } /** @@ -375,11 +436,14 @@ public void testNumericSetObject() throws SQLException { numericValues2 = new String[numericValues.length]; System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - dropTables(stmt); - createNumericTable(); - populateNumericSetObject(numericValues); - testNumeric(null, numericValues, false); - testNumeric(stmt, numericValues2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericSetObject(numericValues); + testNumeric(null, numericValues, false); + testNumeric(stmt, numericValues2, false); + } } /** @@ -389,17 +453,19 @@ public void testNumericSetObject() throws SQLException { */ @Test public void testNumericSetObjectWithJDBCTypes() throws SQLException { - skipTestForJava7(); - numericValues = createNumericValues(nullable); - numericValues2 = new String[numericValues.length]; - System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); - - dropTables(stmt); - createNumericTable(); - populateNumericSetObjectWithJDBCTypes(numericValues); - testNumeric(stmt, numericValues, false); - testNumeric(null, numericValues2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + numericValues = createNumericValues(nullable); + numericValues2 = new String[numericValues.length]; + System.arraycopy(numericValues, 0, numericValues2, 0, numericValues.length); + + dropTables(stmt); + createNumericTable(); + populateNumericSetObjectWithJDBCTypes(numericValues); + testNumeric(stmt, numericValues, false); + testNumeric(null, numericValues2, false); + } } /** @@ -418,11 +484,14 @@ public void testNumericSpecificSetterMaxValue() throws SQLException { "214748.3647", "922337203685477.5807", "999999999999999999999999.9999", "999999999999999999999999.9999"}; - dropTables(stmt); - createNumericTable(); - populateNumeric(numericValuesBoundaryPositive); - testNumeric(stmt, numericValuesBoundaryPositive, false); - testNumeric(null, numericValuesBoundaryPositive2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumeric(numericValuesBoundaryPositive); + testNumeric(stmt, numericValuesBoundaryPositive, false); + testNumeric(null, numericValuesBoundaryPositive2, false); + } } /** @@ -441,11 +510,14 @@ public void testNumericSpecificSetterMinValue() throws SQLException { "-214748.3648", "-922337203685477.5808", "999999999999999999999999.9999", "999999999999999999999999.9999"}; - dropTables(stmt); - createNumericTable(); - populateNumeric(numericValuesBoundaryNegtive); - testNumeric(stmt, numericValuesBoundaryNegtive, false); - testNumeric(null, numericValuesBoundaryNegtive2, false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumeric(numericValuesBoundaryNegtive); + testNumeric(stmt, numericValuesBoundaryNegtive, false); + testNumeric(null, numericValuesBoundaryNegtive2, false); + } } /** @@ -461,11 +533,14 @@ public void testNumericSpecificSetterNull() throws SQLException { numericValuesNull2 = new String[numericValuesNull.length]; System.arraycopy(numericValuesNull, 0, numericValuesNull2, 0, numericValuesNull.length); - dropTables(stmt); - createNumericTable(); - populateNumericNullCase(numericValuesNull); - testNumeric(stmt, numericValuesNull, true); - testNumeric(null, numericValuesNull2, true); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericNullCase(numericValuesNull); + testNumeric(stmt, numericValuesNull, true); + testNumeric(null, numericValuesNull2, true); + } nullable = false; RandomData.returnNull = false; @@ -484,11 +559,14 @@ public void testNumericSpecificSetterSetObjectNull() throws SQLException { numericValuesNull2 = new String[numericValuesNull.length]; System.arraycopy(numericValuesNull, 0, numericValuesNull2, 0, numericValuesNull.length); - dropTables(stmt); - createNumericTable(); - populateNumericSetObjectNull(); - testNumeric(stmt, numericValuesNull, true); - testNumeric(null, numericValuesNull2, true); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericSetObjectNull(); + testNumeric(stmt, numericValuesNull, true); + testNumeric(null, numericValuesNull2, true); + } nullable = false; RandomData.returnNull = false; @@ -507,17 +585,23 @@ public void testNumericNormalization() throws SQLException { String[] numericValuesNormalization2 = {"true", "1", "127", "100", "100", "1.123", "1.123", "1.123", "123456789123456789", "12345.12345", "987654321123456789", "567812.78", "7812.7812", "7812.7812", "999999999999999999999999.9999", "999999999999999999999999.9999"}; - dropTables(stmt); - createNumericTable(); - populateNumericNormalCase(numericValuesNormalization); - testNumeric(stmt, numericValuesNormalization, false); - testNumeric(null, numericValuesNormalization2, false); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); + createNumericTable(); + populateNumericNormalCase(numericValuesNormalization); + testNumeric(stmt, numericValuesNormalization, false); + testNumeric(null, numericValuesNormalization2, false); + } } private void testChar(SQLServerStatement stmt, String[] values) throws SQLException { - String sql = "select * from " + charTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(charTable); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); while (rs.next()) { @@ -526,12 +610,16 @@ private void testChar(SQLServerStatement stmt, String[] values) throws SQLExcept } } } + } private void testBinary(SQLServerStatement stmt, LinkedList values) throws SQLException { - String sql = "select * from " + binaryTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(binaryTable); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); while (rs.next()) { @@ -544,9 +632,12 @@ private void testBinary(SQLServerStatement stmt, LinkedList values) thro } private void testDate(SQLServerStatement stmt, LinkedList values1) throws SQLException { - String sql = "select * from " + dateTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(dateTable); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); while (rs.next()) { @@ -925,9 +1016,12 @@ private void testGetDate(ResultSet rs, int numberOfColumns, LinkedList v } private void testNumeric(Statement stmt, String[] numericValues, boolean isNull) throws SQLException { - String sql = "select * from " + numericTable; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable); + + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { try (SQLServerResultSet rs = (stmt == null) ? (SQLServerResultSet) pstmt.executeQuery() : (SQLServerResultSet) stmt.executeQuery(sql)) { int numberOfColumns = rs.getMetaData().getColumnCount(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java index 3d1e0d354f..7a343047f9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigDecimal; +import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; @@ -20,10 +21,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; /** @@ -61,101 +65,125 @@ public class PrecisionScaleTest extends AESetup { @Test public void testNumericPrecision8Scale2() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] numeric = {"1.12345", "12345.12", "567.70"}; + String[] numeric = {"1.12345", "12345.12", "567.70"}; - createNumericPrecisionTable(30, 8, 2); - populateNumericNormalCase(numeric, 8, 2); - populateNumericSetObject(numeric, 8, 2); + createNumericPrecisionTable(30, 8, 2); + populateNumericNormalCase(numeric, 8, 2); + populateNumericSetObject(numeric, 8, 2); - testNumeric(numeric); + testNumeric(numeric); + } } @Test public void testDateScale2() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateNormalCase = {GMTDate + ".18", GMTDate + ".1770000", - dateTimeOffsetExpectedValue + ".1770000 +00:01", GMTDateWithoutDate + ".1770000", - GMTDateWithoutDate + ".18", dateTimeOffsetExpectedValue + ".18 +00:01"}; - String[] dateSetObject = {GMTDate + ".18", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", - GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + ".18 +00:01"}; + String[] dateNormalCase = {GMTDate + ".18", GMTDate + ".1770000", + dateTimeOffsetExpectedValue + ".1770000 +00:01", GMTDateWithoutDate + ".1770000", + GMTDateWithoutDate + ".18", dateTimeOffsetExpectedValue + ".18 +00:01"}; + String[] dateSetObject = {GMTDate + ".18", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", + GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + ".18 +00:01"}; - createDatePrecisionTable(2); - populateDateNormalCase(2); - populateDateSetObject(2); + createDatePrecisionTable(2); + populateDateNormalCase(2); + populateDateSetObject(2); - testDate(dateNormalCase, dateSetObject); + testDate(dateNormalCase, dateSetObject); + } } @Test public void testNumericPrecision8Scale0() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] numeric2 = {"1.12345", "12345", "567"}; + String[] numeric2 = {"1.12345", "12345", "567"}; - createNumericPrecisionTable(30, 8, 0); - populateNumericNormalCase(numeric2, 8, 0); - populateNumericSetObject(numeric2, 8, 0); + createNumericPrecisionTable(30, 8, 0); + populateNumericNormalCase(numeric2, 8, 0); + populateNumericSetObject(numeric2, 8, 0); - testNumeric(numeric2); + testNumeric(numeric2); + } } @Test public void testDateScale0() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateNormalCase2 = {GMTDate, GMTDate + ".1770000", dateTimeOffsetExpectedValue + ".1770000 +00:01", - GMTDateWithoutDate + ".1770000", GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; - String[] dateSetObject2 = {GMTDate + ".0", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", - GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; + String[] dateNormalCase2 = {GMTDate, GMTDate + ".1770000", dateTimeOffsetExpectedValue + ".1770000 +00:01", + GMTDateWithoutDate + ".1770000", GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; + String[] dateSetObject2 = {GMTDate + ".0", GMTDate + ".177", dateTimeOffsetExpectedValue + ".177 +00:01", + GMTDateWithoutDate, GMTDateWithoutDate, dateTimeOffsetExpectedValue + " +00:01"}; - createDatePrecisionTable(0); - populateDateNormalCase(0); - populateDateSetObject(0); + createDatePrecisionTable(0); + populateDateNormalCase(0); + populateDateSetObject(0); - testDate(dateNormalCase2, dateSetObject2); + testDate(dateNormalCase2, dateSetObject2); + } } @Test public void testNumericPrecision8Scale2Null() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] numericNull = {"null", "null", "null"}; + String[] numericNull = {"null", "null", "null"}; - createNumericPrecisionTable(30, 8, 2); - populateNumericSetObjectNull(8, 2); + createNumericPrecisionTable(30, 8, 2); + populateNumericSetObjectNull(8, 2); - testNumeric(numericNull); + testNumeric(numericNull); + } } @Test public void testDateScale2Null() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; + String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; - createDatePrecisionTable(2); - populateDateSetObjectNull(2); + createDatePrecisionTable(2); + populateDateSetObjectNull(2); - testDate(dateSetObjectNull, dateSetObjectNull); + testDate(dateSetObjectNull, dateSetObjectNull); + } } @Test public void testDateScale5Null() throws Exception { - dropTables(stmt); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropTables(stmt); - String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; + String[] dateSetObjectNull = {"null", "null", "null", "null", "null", "null"}; - createDatePrecisionTable(5); - populateDateNormalCaseNull(5); - testDate(dateSetObjectNull, dateSetObjectNull); + createDatePrecisionTable(5); + populateDateNormalCaseNull(5); + testDate(dateSetObjectNull, dateSetObjectNull); + } } private void testNumeric(String[] numeric) throws SQLException { - try (ResultSet rs = stmt.executeQuery("select * from " + numericTable)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable))) { int numberOfColumns = rs.getMetaData().getColumnCount(); ArrayList skipMax = new ArrayList<>(); @@ -170,7 +198,9 @@ private void testNumeric(String[] numeric) throws SQLException { private void testDate(String[] dateNormalCase, String[] dateSetObject) throws Exception { - try (ResultSet rs = stmt.executeQuery("select * from " + dateTable)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); SQLServerStatement stmt = (SQLServerStatement) con.createStatement(); + ResultSet rs = stmt.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(dateTable))) { int numberOfColumns = rs.getMetaData().getColumnCount(); ArrayList skipMax = new ArrayList<>(); @@ -335,11 +365,13 @@ private void testGetDate(ResultSet rs, int numberOfColumns, String[] dates) thro } private void populateDateNormalCase(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { @@ -377,11 +409,13 @@ private void populateDateNormalCase(int scale) throws SQLException { } private void populateDateNormalCaseNull(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { @@ -418,10 +452,13 @@ private void populateDateNormalCaseNull(int scale) throws SQLException { } private void populateNumericNormalCase(String[] numeric, int precision, int scale) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // float(30) for (int i = 1; i <= 3; i++) { @@ -443,10 +480,13 @@ private void populateNumericNormalCase(String[] numeric, int precision, int scal } private void populateNumericSetObject(String[] numeric, int precision, int scale) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // float(30) for (int i = 1; i <= 3; i++) { @@ -469,10 +509,13 @@ private void populateNumericSetObject(String[] numeric, int precision, int scale } private void populateNumericSetObjectNull(int precision, int scale) throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // float(30) for (int i = 1; i <= 3; i++) { @@ -495,11 +538,13 @@ private void populateNumericSetObjectNull(int precision, int scale) throws SQLEx } private void populateDateSetObject(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { @@ -538,11 +583,13 @@ private void populateDateSetObject(int scale) throws SQLException { } private void populateDateSetObjectNull(int scale) throws SQLException { - String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," - + "?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?,?,?," + + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, - stmtColEncSetting)) { + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConnectionString, + AEInfo); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) TestUtils.getPreparedStmt(con, sql, + stmtColEncSetting)) { // datetime2(5) for (int i = 1; i <= 3; i++) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java new file mode 100644 index 0000000000..d6b9ee1207 --- /dev/null +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/RegressionAlwaysEncryptedTest.java @@ -0,0 +1,262 @@ +/* + * Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made + * available under the terms of the MIT License. See the LICENSE file in the project root for more information. + */ +package com.microsoft.sqlserver.jdbc.AlwaysEncrypted; + +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; +import java.sql.SQLException; +import java.sql.Statement; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.microsoft.sqlserver.jdbc.RandomUtil; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; + + +@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( + connectionString + ";trustservercertificate=true;columnEncryptionSetting=enabled;", AEInfo); + Statement stmt = connection.createStatement()) { + dropTables(stmt); + + createNumericTable(stmt); + populateNumericTable(connection); + verifyNumericTable(connection, false); + + dropTables(stmt); + createDateTable(stmt); + populateDateTable(connection); + verifyDateTable(connection); + + dropTables(stmt); + createNumericTable(stmt); + populateNumericTableWithNull(connection); + verifyNumericTable(connection, true); + + dropTables(stmt); + } + } + + @Test + public void alwaysEncrypted2() throws SQLException { + try (Connection connection = DriverManager.getConnection( + connectionString + ";trustservercertificate=true;columnEncryptionSetting=enabled;", AEInfo); + Statement stmt = connection.createStatement()) { + dropTables(stmt); + + createCharTable(stmt); + populateCharTable(connection); + verifyCharTable(connection); + + dropTables(stmt); + createDateTable(stmt); + populateDateTable(connection); + verifyDateTable(connection); + + dropTables(stmt); + createNumericTable(stmt); + populateNumericTableSpecificSetter(connection); + verifyNumericTable(connection, false); + + dropTables(stmt); + } + } + + private void populateDateTable(Connection connection) throws SQLException { + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " values( " + "?" + ")"; + try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { + sqlPstmt.setObject(1, date); + sqlPstmt.executeUpdate(); + } + } + + private void populateCharTable(Connection connection) throws SQLException { + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?,?,?,?,?,?" + + ")"; + try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { + sqlPstmt.setObject(1, "hi"); + sqlPstmt.setObject(2, "sample"); + sqlPstmt.setObject(3, "hey"); + sqlPstmt.setObject(4, "test"); + sqlPstmt.setObject(5, "hello"); + sqlPstmt.setObject(6, "caching"); + sqlPstmt.executeUpdate(); + } + } + + private void populateNumericTable(Connection connection) throws SQLException { + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + + " values(?,?,?,?,?,?,?,?,?)"; + try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { + sqlPstmt.setObject(1, true); + sqlPstmt.setObject(2, false); + sqlPstmt.setObject(3, true); + Integer value = 255; + sqlPstmt.setObject(4, value.shortValue(), JDBCType.TINYINT); + sqlPstmt.setObject(5, value.shortValue(), JDBCType.TINYINT); + sqlPstmt.setObject(6, value.shortValue(), JDBCType.TINYINT); + sqlPstmt.setObject(7, Short.valueOf("127"), JDBCType.SMALLINT); + sqlPstmt.setObject(8, Short.valueOf("127"), JDBCType.SMALLINT); + sqlPstmt.setObject(9, Short.valueOf("127"), JDBCType.SMALLINT); + sqlPstmt.executeUpdate(); + } + } + + private void populateNumericTableSpecificSetter(Connection connection) throws SQLException { + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + + "?,?,?,?,?,?,?,?,?" + ")"; + try (PreparedStatement sqlPstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, connection.getHoldability())) { + sqlPstmt.setBoolean(1, true); + sqlPstmt.setBoolean(2, false); + sqlPstmt.setBoolean(3, true); + Integer value = 255; + sqlPstmt.setShort(4, value.shortValue()); + sqlPstmt.setShort(5, value.shortValue()); + sqlPstmt.setShort(6, value.shortValue()); + sqlPstmt.setByte(7, Byte.valueOf("127")); + sqlPstmt.setByte(8, Byte.valueOf("127")); + sqlPstmt.setByte(9, Byte.valueOf("127")); + sqlPstmt.executeUpdate(); + } + } + + private void populateNumericTableWithNull(Connection connection) throws SQLException { + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " 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); + sqlPstmt.setObject(2, null, java.sql.Types.BIT); + sqlPstmt.setObject(3, null, java.sql.Types.BIT); + sqlPstmt.setObject(4, null, java.sql.Types.TINYINT); + sqlPstmt.setObject(5, null, java.sql.Types.TINYINT); + sqlPstmt.setObject(6, null, java.sql.Types.TINYINT); + sqlPstmt.setObject(7, null, java.sql.Types.SMALLINT); + sqlPstmt.setObject(8, null, java.sql.Types.SMALLINT); + sqlPstmt.setObject(9, null, java.sql.Types.SMALLINT); + sqlPstmt.executeUpdate(); + } + } + + 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))) { + while (rs.next()) { + // VSTS BUG 5268 + // assertEquals(date.getTime(), ((Date) rs.getObject(1)).getTime()); + } + } + } + + 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))) { + while (rs.next()) { + assertEquals("hi ", rs.getObject(1)); + assertEquals("sample ", rs.getObject(2)); + assertEquals("hey ", rs.getObject(3)); + assertEquals("test", rs.getObject(4)); + assertEquals("hello", rs.getObject(5)); + assertEquals("caching", rs.getObject(6)); + } + } + } + + 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))) { + while (rs.next()) { + if (isNull) { + assertEquals(null, rs.getObject(1)); + assertEquals(null, rs.getObject(2)); + assertEquals(null, rs.getObject(3)); + assertEquals(null, rs.getObject(4)); + assertEquals(null, rs.getObject(5)); + assertEquals(null, rs.getObject(6)); + assertEquals(null, rs.getObject(7)); + assertEquals(null, rs.getObject(8)); + assertEquals(null, rs.getObject(9)); + } else { + assertEquals(true, rs.getObject(1)); + assertEquals(false, rs.getObject(2)); + assertEquals(true, rs.getObject(3)); + assertEquals((short) 255, rs.getObject(4)); + assertEquals((short) 255, rs.getObject(5)); + assertEquals((short) 255, rs.getObject(6)); + assertEquals((short) 127, rs.getObject(7)); + assertEquals((short) 127, rs.getObject(8)); + assertEquals((short) 127, rs.getObject(9)); + } + } + } + } + + private void createDateTable(Statement stmt) throws SQLException { + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(dateTable) + " (" + + "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") NULL," + ");"; + stmt.execute(sql); + } + + private void createCharTable(Statement stmt) throws SQLException { + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (" + + "PlainChar char(20) null," + + "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") NULL," + + "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") 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," + + "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," + ");"; + stmt.execute(sql); + } + + private void createNumericTable(Statement stmt) throws SQLException { + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + "PlainBit bit null," + + "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") NULL," + + "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") NULL," + "PlainTinyint tinyint null," + + "RandomizedTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") NULL," + + "DeterministicTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") NULL," + "PlainSmallint smallint null," + + "RandomizedSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") NULL," + + "DeterministicSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " + + cekName + ") 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); + } +} diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java b/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java index e1f6818e88..e73650b97a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/ComparisonUtil.java @@ -18,10 +18,9 @@ import java.sql.Timestamp; import java.util.Calendar; -import com.microsoft.sqlserver.jdbc.SQLServerResultSetMetaData; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBResultSet; +import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; @@ -37,10 +36,10 @@ public class ComparisonUtil { */ public static void compareSrcTableAndDestTableIgnoreRowOrder(DBConnection con, DBTable srcTable, DBTable destTable) throws SQLException { - try (DBStatement stmt = con.createStatement(); + try (DBStatement stmt = con.createStatement(); DBStatement stmt2 = con.createStatement(); DBResultSet srcResultSetCount = stmt .executeQuery("SELECT COUNT(*) FROM " + srcTable.getEscapedTableName() + ";"); - DBResultSet dstResultSetCount = stmt + DBResultSet dstResultSetCount = stmt2 .executeQuery("SELECT COUNT(*) FROM " + destTable.getEscapedTableName() + ";")) { srcResultSetCount.next(); dstResultSetCount.next(); @@ -58,7 +57,7 @@ public static void compareSrcTableAndDestTableIgnoreRowOrder(DBConnection con, D try (DBResultSet srcResultSet = stmt.executeQuery( "SELECT * FROM " + srcTable.getEscapedTableName() + " ORDER BY [" + srcTable.getColumnName(1) + "], [" + srcTable.getColumnName(2) + "],[" + srcTable.getColumnName(3) + "];"); - DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destTable.getEscapedTableName() + DBResultSet dstResultSet = stmt2.executeQuery("SELECT * FROM " + destTable.getEscapedTableName() + " ORDER BY [" + destTable.getColumnName(1) + "], [" + destTable.getColumnName(2) + "],[" + destTable.getColumnName(3) + "];")) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java index f8b6279ed2..8b2ca84b4b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestResource.java @@ -92,7 +92,7 @@ protected Object[][] getContents() { {"R_shouldThrowException", "Exception should have been thrown"}, {"R_tcpipConnectionToHost", "The TCP/IP connection to the host"}, {"R_queryTimedOut", "The query has timed out."}, {"R_readTimedOut", "Read timed out"}, - {"R_unexpectedErrorMessage", "Unexpected error message occured!"}, + {"R_unexpectedErrorMessage", "Unexpected error message occurred!"}, {"R_warningsNotFound", "Warnings not found!"}, {"R_warningsFound", "Warnings found!"}, {"R_causeShouldNotBeNull", "Cause should not be null."}, {"R_causeShouldBeInstance", "Cause should be instance of {0}."}, diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java index eb3fe3b884..bb7d317d42 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/TestUtils.java @@ -259,9 +259,8 @@ public DBNCharacterStream(String value) { public static String getCurrentClassPath() { try { String className = new Object() {}.getClass().getEnclosingClass().getName(); - String location = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath() - + "/"; - URI uri = new URI(location.toString()); + String location = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath(); + URI uri = new URI(location + "/"); return uri.getPath(); } catch (Exception e) { fail("Failed to get CSV file path. " + e.getMessage()); @@ -381,38 +380,6 @@ static byte CharToHex(char value) throws SQLException { return ret; } - /** - * Utility function for safely closing open resultset/statement/connection - * - * @param ResultSet - * @param Statement - * @param Connection - */ - public static void close(ResultSet rs, Statement stmt, Connection con) { - if (rs != null) { - try { - rs.close(); - - } catch (SQLException e) { - System.out.println("The result set cannot be closed."); - } - } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - System.out.println("The statement cannot be closed."); - } - } - if (con != null) { - try { - con.close(); - } catch (SQLException e) { - System.out.println("The data source connection cannot be closed."); - } - } - } - /** * Utility method for a callable statement * diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypesTest.java similarity index 98% rename from src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java rename to src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypesTest.java index a18625365c..2fdd955a3a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypesTest.java @@ -24,7 +24,7 @@ @RunWith(JUnitPlatform.class) -public class BulkCopyAllTypes extends AbstractTest { +public class BulkCopyAllTypesTest extends AbstractTest { private static DBTable tableSrc = null; private static DBTable tableDest = null; 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 6ec94f0910..0da47193c0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -120,13 +120,14 @@ public void testExplicitCM() { @DisplayName("BulkCopy:test unicode column mapping") public void testUnicodeCM() { DBTable sourceTableUnicode = null; + DBTable destTableUnicode = null; try { // create source unicode table sourceTableUnicode = new DBTable(true, true); stmt.createTable(sourceTableUnicode); // create destination unicode table with same schema as source - DBTable destTableUnicode = sourceTableUnicode.cloneSchema(); + destTableUnicode = sourceTableUnicode.cloneSchema(); stmt.createTable(destTableUnicode); // set up bulkCopy with explicit column mapping @@ -159,6 +160,9 @@ public void testUnicodeCM() { if (null != sourceTableUnicode) { dropTable(sourceTableUnicode.getEscapedTableName()); } + if (null != destTableUnicode) { + dropTable(destTableUnicode.getEscapedTableName()); + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java index e0d264e5aa..3ce050a65e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -17,15 +17,16 @@ import java.util.Properties; import java.util.TimeZone; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; -import org.junit.jupiter.api.AfterAll; import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -43,8 +44,8 @@ public class BulkCopyResultSetCursorTest extends AbstractTest { static String[] expectedTimestampStrings = {"2015-06-03 13:35:33.4610000", "2442-09-19 01:59:43.9990000", "2017-04-02 08:58:53.0000000"}; - private static String srcTable = null; - private static String desTable = null; + private static String srcTable = RandomUtil.getIdentifier("BulkCopyResultSetCursorTest_SourceTable"); + private static String desTable = RandomUtil.getIdentifier("BulkCopyResultSetCursorTest_DestinationTable"); /** * Test a previous failure when using server cursor and using the same connection to create Bulk Copy and result @@ -68,9 +69,10 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro populateSourceTable(); try (Statement stmt2 = conn.createStatement(resultSetType, resultSetConcurrency); - ResultSet rs = stmt2.executeQuery("select * from " + srcTable); + ResultSet rs = stmt2 + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { - bulkCopy.setDestinationTableName(desTable); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length); @@ -94,10 +96,10 @@ public void testSelectMethodSetToCursor() throws SQLException { createTables(stmt); populateSourceTable(); - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable); + try (ResultSet rs = stmt.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { - bulkCopy.setDestinationTableName(desTable); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length); @@ -119,28 +121,29 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { populateSourceTable(); try (Statement stmt1 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt1.executeQuery("select * from " + srcTable)) { + ResultSet rs = stmt1 + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable))) { try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { - bulkCopy.setDestinationTableName(desTable); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length); } rs.beforeFirst(); try (SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn)) { - bulkCopy1.setDestinationTableName(desTable); + bulkCopy1.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy1.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length * 2); } rs.beforeFirst(); try (SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn)) { - bulkCopy2.setDestinationTableName(desTable); + bulkCopy2.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy2.writeToServer(rs); verifyDestinationTableData(expectedBigDecimals.length * 3); } - String sql = "insert into " + desTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(desTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); try (SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { for (int i = 0; i < expectedBigDecimals.length; i++) { @@ -153,9 +156,11 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { verifyDestinationTableData(expectedBigDecimals.length * 4); } try (Statement stmt2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, - ResultSet.CONCUR_UPDATABLE); ResultSet rs2 = stmt2.executeQuery("select * from " + srcTable); + ResultSet.CONCUR_UPDATABLE); + ResultSet rs2 = stmt2 + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn)) { - bulkCopy3.setDestinationTableName(desTable); + bulkCopy3.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(desTable)); bulkCopy3.writeToServer(rs2); verifyDestinationTableData(expectedBigDecimals.length * 5); } @@ -164,8 +169,8 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { } private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { - try (Connection conn = DriverManager.getConnection(connectionString); - ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + try (Connection conn = DriverManager.getConnection(connectionString); ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable))) { int expectedArrayLength = expectedBigDecimals.length; @@ -187,7 +192,7 @@ private static void verifyDestinationTableData(int expectedNumberOfRows) throws } private static void populateSourceTable() throws SQLException { - String sql = "insert into " + srcTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); try (Connection conn = DriverManager.getConnection(connectionString); @@ -205,26 +210,18 @@ private static void populateSourceTable() throws SQLException { private static void dropTables(Statement stmt) throws SQLException { if (null != srcTable) { - TestUtils.dropTableIfExists(srcTable, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); } if (null != desTable) { - TestUtils.dropTableIfExists(desTable, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable), stmt); } } private static void createTables(Statement stmt) throws SQLException { - - if (null == srcTable) { - srcTable = "[BulkCopyResultSetCursorTest_Source_" + RandomUtil.getIdentifier("table") + "]"; - } - if (null == desTable) { - desTable = "[BulkCopyResultSetCursorTest_Destination_" + RandomUtil.getIdentifier("table") + "]"; - } - - String sql = "create table " + srcTable + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); - sql = "create table " + desTable + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java index 2b769daf0f..f0a1468ea1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java @@ -9,8 +9,8 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; +import java.sql.Connection; import java.sql.DriverManager; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -22,7 +22,6 @@ import java.util.Map; import java.util.Set; -import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -30,23 +29,23 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; -import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class ISQLServerBulkRecordIssuesTest extends AbstractTest { - static Statement stmt = null; - static PreparedStatement pStmt = null; + // static Statement stmt = null; static String query; - static SQLServerConnection con = null; - static String srcTable = "sourceTable"; - static String destTable = "destTable"; + static String srcTable = RandomUtil.getIdentifier("sourceTable"); + static String destTable = RandomUtil.getIdentifier("destTable"); + String variation; /** @@ -58,20 +57,22 @@ public class ISQLServerBulkRecordIssuesTest extends AbstractTest { public void testVarchar() throws Exception { variation = "testVarchar"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (smallDATA varchar(2))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - bcOperation.close(); - fail(TestResource.getResource("R_expectedFailPassed")); - } catch (Exception e) { - if (e instanceof SQLException) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA varchar(2))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + bcOperation.close(); + fail(TestResource.getResource("R_expectedFailPassed")); + } catch (Exception e) { + if (e instanceof SQLException) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -86,16 +87,19 @@ public void testSmalldatetime() throws Exception { variation = "testSmalldatetime"; BulkData bData = new BulkData(variation); String value = ("1954-05-22 02:44:00.0").toString(); - query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - - try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { - while (rs.next()) { - assertEquals(rs.getString(1), value); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA smalldatetime)"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(destTable))) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } } } } @@ -111,22 +115,24 @@ public void testSmalldatetimeOutofRange() throws Exception { variation = "testSmalldatetimeOutofRange"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - fail("BulkCopy executed for testSmalldatetimeOutofRange when it it was expected to fail"); - } catch (Exception e) { - if (e instanceof SQLException) { - MessageFormat form = new MessageFormat(TestResource.getResource("R_conversionFailed")); - Object[] msgArgs = {"character string", "smalldatetime"}; - - assertTrue(e.getMessage().contains(form.format(msgArgs)), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (smallDATA smalldatetime)"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + fail("BulkCopy executed for testSmalldatetimeOutofRange when it it was expected to fail"); + } catch (Exception e) { + if (e instanceof SQLException) { + MessageFormat form = new MessageFormat(TestResource.getResource("R_conversionFailed")); + Object[] msgArgs = {"character string", "smalldatetime"}; + + assertTrue(e.getMessage().contains(form.format(msgArgs)), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -140,19 +146,21 @@ public void testSmalldatetimeOutofRange() throws Exception { public void testBinaryColumnAsByte() throws Exception { variation = "testBinaryColumnAsByte"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (col1 binary(5))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - fail(TestResource.getResource("R_expectedFailPassed")); - } catch (Exception e) { - if (e instanceof SQLException) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + fail(TestResource.getResource("R_expectedFailPassed")); + } catch (Exception e) { + if (e instanceof SQLException) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -166,19 +174,21 @@ public void testBinaryColumnAsByte() throws Exception { public void testBinaryColumnAsString() throws Exception { variation = "testBinaryColumnAsString"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (col1 binary(5))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - fail(TestResource.getResource("R_expectedFailPassed")); - } catch (Exception e) { - if (e instanceof SQLException) { - assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), - TestResource.getResource("R_invalidErrorMessage") + e.toString()); - } else { - fail(e.getMessage()); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + fail(TestResource.getResource("R_expectedFailPassed")); + } catch (Exception e) { + if (e instanceof SQLException) { + assertTrue(e.getMessage().contains(TestResource.getResource("R_givenValueType")), + TestResource.getResource("R_invalidErrorMessage") + e.toString()); + } else { + fail(e.getMessage()); + } } } } @@ -192,20 +202,23 @@ public void testBinaryColumnAsString() throws Exception { public void testSendValidValueforBinaryColumnAsString() throws Exception { variation = "testSendValidValueforBinaryColumnAsString"; BulkData bData = new BulkData(variation); - query = "CREATE TABLE " + destTable + " (col1 binary(5))"; - stmt.executeUpdate(query); - - try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - - try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { - while (rs.next()) { - assertEquals(rs.getString(1), "0101010000"); + query = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (col1 binary(5))"; + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + stmt.executeUpdate(query); + + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTable)); + bcOperation.writeToServer(bData); + + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(destTable))) { + while (rs.next()) { + assertEquals(rs.getString(1), "0101010000"); + } } + } catch (Exception e) { + fail(e.getMessage()); } - } catch (Exception e) { - fail(e.getMessage()); } } @@ -218,10 +231,10 @@ public void testSendValidValueforBinaryColumnAsString() throws Exception { */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { - con = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = con.createStatement(); - TestUtils.dropTableIfExists(destTable, stmt); - TestUtils.dropTableIfExists(srcTable, stmt); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); + } } /** @@ -231,20 +244,11 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterEach public void afterEachTests() throws SQLException { - TestUtils.dropTableIfExists(destTable, stmt); - TestUtils.dropTableIfExists(srcTable, stmt); - } - - @AfterAll - public static void afterAllTests() throws SQLException { - if (null != stmt) { - stmt.close(); - } - if (null != con) { - con.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/BvtTest.java similarity index 95% rename from src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java rename to src/test/java/com/microsoft/sqlserver/jdbc/bvt/BvtTest.java index 4c7d03c8a1..0d5f768d4e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/BvtTest.java @@ -14,24 +14,31 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.junit.jupiter.api.BeforeAll; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.DBConnection; +import com.microsoft.sqlserver.testframework.DBStatement; +import com.microsoft.sqlserver.testframework.DBTable; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.TestResource; -import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBPreparedStatement; import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBResultSetTypes; -import com.microsoft.sqlserver.testframework.DBStatement; @RunWith(JUnitPlatform.class) @DisplayName("BVT Test") -public class bvtTest extends bvtTestSetup { +public class BvtTest extends AbstractTest { private static String driverNamePattern = "Microsoft JDBC Driver \\d.\\d for SQL Server"; + static DBTable table1; + static DBTable table2; /** * Connect to specified server and close the connection @@ -426,4 +433,17 @@ public static void terminate() throws SQLException { + table2.getEscapedTableName()); } } + + @BeforeAll + public static void init() throws SQLException { + try (DBConnection conn = new DBConnection(connectionString); DBStatement stmt = conn.createStatement()) { + // create tables + table1 = new DBTable(true); + stmt.createTable(table1); + stmt.populateTable(table1); + table2 = new DBTable(true); + stmt.createTable(table2); + stmt.populateTable(table2); + } + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java deleted file mode 100644 index 404879fd23..0000000000 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made - * available under the terms of the MIT License. See the LICENSE file in the project root for more information. - */ -package com.microsoft.sqlserver.jdbc.bvt; - -import java.sql.SQLException; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; - -import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBStatement; -import com.microsoft.sqlserver.testframework.DBTable; - - -/** - * - * Setting up the test - */ -@RunWith(JUnitPlatform.class) -public class bvtTestSetup extends AbstractTest { - - static DBTable table1; - static DBTable table2; - - @BeforeAll - public static void init() throws SQLException { - try (DBConnection conn = new DBConnection(connectionString); DBStatement stmt = conn.createStatement()) { - // create tables - table1 = new DBTable(true); - stmt.createTable(table1); - stmt.populateTable(table1); - table2 = new DBTable(true); - stmt.createTable(table2); - stmt.populateTable(table2); - } - } -} diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java index ed0249250c..fde8003532 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -19,11 +19,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; /** @@ -31,13 +33,10 @@ */ @RunWith(JUnitPlatform.class) public class CallableStatementTest extends AbstractTest { - private static String tableNameGUID = "uniqueidentifier_Table"; - private static String outputProcedureNameGUID = "uniqueidentifier_SP"; - private static String setNullProcedureName = "CallableStatementTest_setNull_SP"; - private static String inputParamsProcedureName = "CallableStatementTest_inputParams_SP"; - - private static Connection connection = null; - private static Statement stmt = null; + private static String tableNameGUID = RandomUtil.getIdentifier("uniqueidentifier_Table"); + private static String outputProcedureNameGUID = RandomUtil.getIdentifier("uniqueidentifier_SP"); + private static String setNullProcedureName = RandomUtil.getIdentifier("CallableStatementTest_setNull_SP"); + private static String inputParamsProcedureName = RandomUtil.getIdentifier("CallableStatementTest_inputParams_SP"); /** * Setup before test @@ -46,18 +45,19 @@ public class CallableStatementTest extends AbstractTest { */ @BeforeAll public static void setupTest() throws SQLException { - connection = DriverManager.getConnection(connectionString); - stmt = connection.createStatement(); - - TestUtils.dropTableIfExists(tableNameGUID, stmt); - TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); - TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); - TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); - - createGUIDTable(stmt); - createGUIDStoredProcedure(stmt); - createSetNullPreocedure(stmt); - createInputParamsProcedure(stmt); + + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(setNullProcedureName), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName), stmt); + + createGUIDTable(stmt); + createGUIDStoredProcedure(stmt); + createSetNullPreocedure(stmt); + createInputParamsProcedure(stmt); + } } /** @@ -68,7 +68,7 @@ public static void setupTest() throws SQLException { @Test public void getStringGUIDTest() throws SQLException { - String sql = "{call " + outputProcedureNameGUID + "(?)}"; + String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID) + "(?)}"; try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql)) { @@ -97,7 +97,7 @@ public void getSetNullWithTypeVarchar() throws SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); ds.setSendStringParametersAsUnicode(true); - String sql = "{? = call " + setNullProcedureName + " (?,?)}"; + String sql = "{? = call " + AbstractSQLGenerator.escapeIdentifier(setNullProcedureName) + " (?,?)}"; try (Connection connection = ds.getConnection(); SQLServerCallableStatement cs = (SQLServerCallableStatement) connection.prepareCall(sql); SQLServerCallableStatement cs2 = (SQLServerCallableStatement) connection.prepareCall(sql)) { @@ -129,7 +129,7 @@ public void getSetNullWithTypeVarchar() throws SQLException { */ @Test public void inputParamsTest() throws SQLException { - String call = "{CALL " + inputParamsProcedureName + " (?,?)}"; + String call = "{CALL " + AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName) + " (?,?)}"; // the historical way: no leading '@', parameter names respected (not positional) try (CallableStatement cs = connection.prepareCall(call)) { @@ -173,39 +173,39 @@ public void inputParamsTest() throws SQLException { */ @AfterAll public static void cleanup() throws SQLException { - TestUtils.dropTableIfExists(tableNameGUID, stmt); - TestUtils.dropProcedureIfExists(outputProcedureNameGUID, stmt); - TestUtils.dropProcedureIfExists(setNullProcedureName, stmt); - TestUtils.dropProcedureIfExists(inputParamsProcedureName, stmt); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { - if (null != stmt) { - stmt.close(); - } - if (null != connection) { - connection.close(); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(setNullProcedureName), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName), stmt); } } private static void createGUIDStoredProcedure(Statement stmt) throws SQLException { - String sql = "CREATE PROCEDURE " + outputProcedureNameGUID - + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " + tableNameGUID + ";"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(outputProcedureNameGUID) + + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableNameGUID) + ";"; stmt.execute(sql); } private static void createGUIDTable(Statement stmt) throws SQLException { - String sql = "CREATE TABLE " + tableNameGUID + " (c1 uniqueidentifier null)"; + String sql = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableNameGUID) + + " (c1 uniqueidentifier null)"; stmt.execute(sql); } private static void createSetNullPreocedure(Statement stmt) throws SQLException { - stmt.execute("create procedure " + setNullProcedureName + stmt.execute("create procedure " + AbstractSQLGenerator.escapeIdentifier(setNullProcedureName) + " (@p1 nvarchar(255), @p2 nvarchar(255) output) as select @p2=@p1 return 0"); } private static void createInputParamsProcedure(Statement stmt) throws SQLException { - String sql = "CREATE PROCEDURE [dbo].[CallableStatementTest_inputParams_SP] " + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputParamsProcedureName) + " @p1 nvarchar(max) = N'parameter1', " + " @p2 nvarchar(max) = N'parameter2' " + "AS " + "BEGIN " + " SET NOCOUNT ON; " + " SELECT @p1 + @p2 AS result; " + "END "; + stmt.execute(sql); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java index 24b12f18e7..00eeb986ab 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -40,14 +40,14 @@ import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.SQLServerDriver; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBTable; @RunWith(JUnitPlatform.class) public class ConnectionDriverTest extends AbstractTest { - // If no retry is done, the function should atleast exit in 5 seconds + // If no retry is done, the function should at least exit in 5 seconds static int threshHoldForNoRetryInMilliseconds = 5000; static int loginTimeOutInSeconds = 10; @@ -307,23 +307,24 @@ public void testDeadConnection() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), TestResource.getResource("R_skipAzure")); - String tableName = null; + String tableName = RandomUtil.getIdentifier("ConnectionTestTable"); try (SQLServerConnection conn = (SQLServerConnection) DriverManager .getConnection(connectionString + ";responseBuffering=adaptive"); Statement stmt = conn.createStatement()) { - tableName = RandomUtil.getIdentifier("Table"); - tableName = DBTable.escapeIdentifier(tableName); - conn.setAutoCommit(false); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); + stmt.executeUpdate( + "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int primary key)"); for (int i = 0; i < 80; i++) { - stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(col1) values (" + + i + ")"); } conn.commit(); try { - stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " - + tableName + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); + stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " as x1, " + + AbstractSQLGenerator.escapeIdentifier(tableName) + + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); } catch (SQLException e) { assertEquals(e.getMessage(), TestResource.getResource("R_connectionReset"), TestResource.getResource("R_unknownException")); @@ -336,7 +337,7 @@ public void testDeadConnection() throws SQLException { try (SQLServerConnection conn = (SQLServerConnection) DriverManager .getConnection(connectionString + ";responseBuffering=adaptive"); Statement stmt = conn.createStatement()) { - stmt.execute("drop table " + tableName); + stmt.execute("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java index 307c9a0c1d..9408f7d3de 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -23,6 +23,7 @@ import javax.sql.PooledConnection; import org.apache.commons.dbcp2.BasicDataSource; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -32,9 +33,9 @@ import com.microsoft.sqlserver.jdbc.SQLServerXADataSource; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBTable; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; @@ -45,16 +46,14 @@ */ @RunWith(JUnitPlatform.class) public class PoolingTest extends AbstractTest { + static String tempTableName = RandomUtil.getIdentifier("#poolingtest"); + static String tableName = RandomUtil.getIdentifier("PoolingTestTable"); + @Test public void testPooling() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), "Skipping test case on Azure SQL."); - String randomTableName = RandomUtil.getIdentifier("table"); - - // make the table a temporary table (will be created in tempdb database) - String tempTableName = "#" + randomTableName; - SQLServerXADataSource XADataSource1 = new SQLServerXADataSource(); XADataSource1.setURL(connectionString); XADataSource1.setDatabaseName("tempdb"); @@ -63,8 +62,8 @@ public void testPooling() throws SQLException { try (Connection conn = pc.getConnection(); Statement stmt = conn.createStatement()) { // create table in tempdb database - stmt.execute("create table [" + tempTableName + "] (myid int)"); - stmt.execute("insert into [" + tempTableName + "] values (1)"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tempTableName) + " (myid int)"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(tempTableName) + " values (1)"); } boolean tempTableFileRemoved = false; @@ -100,14 +99,12 @@ public void testConnectionPoolReget() throws SQLException { @Test public void testConnectionPoolConnFunctions() throws SQLException { - String tableName = RandomUtil.getIdentifier("table"); - tableName = DBTable.escapeIdentifier(tableName); - String sql1 = "if exists (select * from dbo.sysobjects where name = '" + TestUtils.escapeSingleQuotes(tableName) - + "' and type = 'U')\n" + "drop table " + tableName + "\n" + "create table " + tableName + "\n" + "(\n" + + "' and type = 'U')\n" + "drop table " + AbstractSQLGenerator.escapeIdentifier(tableName) + "\n" + + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + "\n" + "(\n" + "wibble_id int primary key not null,\n" + "counter int null\n" + ");"; String sql2 = "if exists (select * from dbo.sysobjects where name = '" + TestUtils.escapeSingleQuotes(tableName) - + "' and type = 'U')\n" + "drop table " + tableName + "\n"; + + "' and type = 'U')\n" + "drop table " + AbstractSQLGenerator.escapeIdentifier(tableName) + "\n"; SQLServerXADataSource ds = new SQLServerXADataSource(); ds.setURL(connectionString); @@ -252,4 +249,17 @@ private static int countTimeoutThreads() { return count; } + + /** + * drop the tables + * + * @throws SQLException + */ + @AfterAll + public static void afterAll() throws SQLException { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tempTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + } + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java index dfdafe31a5..fa402a7d29 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/RequestBoundaryMethodsTest.java @@ -12,9 +12,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.sql.Connection; import java.sql.CallableStatement; -import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -41,6 +39,8 @@ @RunWith(JUnitPlatform.class) public class RequestBoundaryMethodsTest extends AbstractTest { + static String tableName = RandomUtil.getIdentifier("RequestBoundaryTable"); + /** * Tests Request Boundary methods with SQLServerConnection properties that are modifiable through public APIs. * @@ -176,25 +176,23 @@ public void testWarnings() throws SQLException { */ @Test public void testOpenTransactions() throws SQLException { - String tableName = null; - try (SQLServerConnection con = connect(); Statement stmt = con.createStatement()) { if (TestUtils.isJDBC43OrGreater(con)) { - tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundaryTable")); - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col int)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col int)"); con.beginRequest(); con.setAutoCommit(false); - stmt.executeUpdate("INSERT INTO " + tableName + " values(5)"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(5)"); // endRequest() does a rollback here, the value does not get inserted into the table. con.endRequest(); con.commit(); - try (ResultSet rs = con.createStatement().executeQuery("SELECT * from " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { assertTrue(!rs.isBeforeFirst(), "Should not have returned a result set."); } finally { if (null != tableName) { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -211,8 +209,6 @@ public void testOpenTransactions() throws SQLException { @SuppressWarnings("resource") @Test public void testStatements() throws SQLException { - String tableName = null; - try (SQLServerConnection con = connect();) { if (TestUtils.isJDBC43OrGreater(con)) { try (Statement stmt1 = con.createStatement()) { @@ -226,7 +222,7 @@ public void testStatements() throws SQLException { assertTrue(!stmt1.isClosed(), "Statement created outside of beginRequest()/endRequest() block should not be closed."); assertTrue(stmt.isClosed(), - "Statment created inside beginRequest()/endRequest() block should be closed after endRequest()."); + "Statement created inside beginRequest()/endRequest() block should be closed after endRequest()."); assertTrue(rs.isClosed(), "ResultSet should be closed after endRequest()."); } } @@ -235,18 +231,19 @@ public void testStatements() throws SQLException { // Multiple statements inside beginRequest()/endRequest() block con.beginRequest(); try (Statement stmt = con.createStatement()) { - tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundary")); - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col int)"); - try (PreparedStatement ps = con.prepareStatement("INSERT INTO " + tableName + " values (?)")) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col int)"); + try (PreparedStatement ps = con.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?)")) { ps.setInt(1, 2); ps.executeUpdate(); - try (Statement stmt1 = con.createStatement(); - ResultSet rs = stmt1.executeQuery("SELECT * FROM " + tableName)) { + try (Statement stmt1 = con.createStatement(); ResultSet rs = stmt1 + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); assertEquals(2, rs.getInt(1)); - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); try (CallableStatement cs = con.prepareCall("{call sp_server_info}")) { cs.execute(); @@ -263,7 +260,7 @@ public void testStatements() throws SQLException { } finally { if (null != tableName) { try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java index 5922ddbe53..cafc5ebb49 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/SSLProtocolTest.java @@ -11,7 +11,6 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; -import java.sql.Statement; import java.text.MessageFormat; import org.junit.jupiter.api.Test; 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 38635f2de8..61a17bea6d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/TimeoutTest.java @@ -9,10 +9,11 @@ import static org.junit.jupiter.api.Assertions.fail; import java.sql.Connection; -import java.sql.Statement; import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.Statement; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; @@ -23,13 +24,14 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class TimeoutTest extends AbstractTest { String randomServer = RandomUtil.getIdentifier("Server"); - String waitForDelaySPName = "waitForDelaySP"; + static String waitForDelaySPName = RandomUtil.getIdentifier("waitForDelaySP"); final int waitForDelaySeconds = 10; @Test @@ -98,7 +100,6 @@ public void testFOInstanceResolution2() throws SQLException { @Test public void testQueryTimeout() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -107,7 +108,7 @@ public void testQueryTimeout() throws Exception { .getConnection(connectionString + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";")) { try (Statement stmt = conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { @@ -136,7 +137,6 @@ public void testQueryTimeout() throws Exception { public void testCancelQueryTimeout() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -145,7 +145,7 @@ public void testCancelQueryTimeout() throws Exception { + ";queryTimeout=" + (waitForDelaySeconds / 2) + ";cancelQueryTimeout=" + waitForDelaySeconds + ";")) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { @@ -173,7 +173,6 @@ public void testCancelQueryTimeout() throws Exception { @Test public void testCancelQueryTimeoutOnStatement() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -183,7 +182,7 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { stmt.setQueryTimeout(waitForDelaySeconds / 2); stmt.setCancelQueryTimeout(waitForDelaySeconds); - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof java.sql.SQLTimeoutException)) { @@ -211,7 +210,6 @@ public void testCancelQueryTimeoutOnStatement() throws Exception { @Test public void testSocketTimeout() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { - dropWaitForDelayProcedure(conn); createWaitForDelayPreocedure(conn); } @@ -220,7 +218,7 @@ public void testSocketTimeout() throws Exception { .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";")) { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof SQLException)) { @@ -241,9 +239,9 @@ public void testSocketTimeout() throws Exception { } } - private void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLException { + private static void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLException { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - TestUtils.dropProcedureIfExists(waitForDelaySPName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } @@ -251,12 +249,18 @@ private void dropWaitForDelayProcedure(SQLServerConnection conn) throws SQLExcep private void createWaitForDelayPreocedure(SQLServerConnection conn) throws SQLException { try (SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - - String sql = "CREATE PROCEDURE " + waitForDelaySPName + " AS" + " BEGIN" + " WAITFOR DELAY '00:00:" - + waitForDelaySeconds + "';" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName) + " AS" + + " BEGIN" + " WAITFOR DELAY '00:00:" + waitForDelaySeconds + "';" + " END"; stmt.execute(sql); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } } + + @AfterAll + public static void cleanup() throws SQLException { + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + dropWaitForDelayProcedure(conn); + } + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java index 1196561888..ffd34ad739 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataForeignKeyTest.java @@ -18,12 +18,14 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -32,13 +34,12 @@ */ @RunWith(JUnitPlatform.class) public class DatabaseMetaDataForeignKeyTest extends AbstractTest { - private static SQLServerConnection conn = null; - private static String table1 = "DatabaseMetaDataForeignKeyTest_table_1"; - private static String table2 = "DatabaseMetaDataForeignKeyTest_table_2"; - private static String table3 = "DatabaseMetaDataForeignKeyTest_table_3"; - private static String table4 = "DatabaseMetaDataForeignKeyTest_table_4"; - private static String table5 = "DatabaseMetaDataForeignKeyTest_table_5"; + private static String table1 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_1"); + private static String table2 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_2"); + private static String table3 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_3"); + private static String table4 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_4"); + private static String table5 = RandomUtil.getIdentifier("DatabaseMetaDataForeignKeyTest_table_5"); private static String schema = null; private static String catalog = null; @@ -50,23 +51,38 @@ public static void setupVariation() throws SQLException { catalog = conn.getCatalog(); schema = conn.getSchema(); - stmt.executeUpdate("if object_id('" + table1 + "','U') is not null drop table " + table1); - - stmt.executeUpdate("if object_id('" + table2 + "','U') is not null drop table " + table2); - stmt.execute("Create table " + table2 + " (c21 int NOT NULL PRIMARY KEY)"); - - stmt.executeUpdate("if object_id('" + table3 + "','U') is not null drop table " + table3); - stmt.execute("Create table " + table3 + " (c31 int NOT NULL PRIMARY KEY)"); - stmt.executeUpdate("if object_id('" + table4 + "','U') is not null drop table " + table4); - stmt.execute("Create table " + table4 + " (c41 int NOT NULL PRIMARY KEY)"); - stmt.executeUpdate("if object_id('" + table5 + "','U') is not null drop table " + table5); - stmt.execute("Create table " + table5 + " (c51 int NOT NULL PRIMARY KEY)"); - stmt.executeUpdate("if object_id('" + table1 + "','U') is not null drop table " + table1); - stmt.execute("Create table " + table1 + " (c11 int primary key," + " c12 int FOREIGN KEY REFERENCES " - + table2 + "(c21) ON DELETE no action ON UPDATE set default," + " c13 int FOREIGN KEY REFERENCES " - + table3 + "(c31) ON DELETE cascade ON UPDATE set null," + " c14 int FOREIGN KEY REFERENCES " - + table4 + "(c41) ON DELETE set null ON UPDATE cascade," + " c15 int FOREIGN KEY REFERENCES " - + table5 + "(c51) ON DELETE set default ON UPDATE no action," + ")"); + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table1) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table1)); + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table2) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table2)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table2) + + " (c21 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table3) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table3)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table3) + + " (c31 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table4) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table4)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table4) + + " (c41 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table5) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table5)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table5) + + " (c51 int NOT NULL PRIMARY KEY)"); + + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(table1) + + "','U') is not null drop table " + AbstractSQLGenerator.escapeIdentifier(table1)); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(table1) + " (c11 int primary key," + + " c12 int FOREIGN KEY REFERENCES " + AbstractSQLGenerator.escapeIdentifier(table2) + + "(c21) ON DELETE no action ON UPDATE set default," + " c13 int FOREIGN KEY REFERENCES " + + AbstractSQLGenerator.escapeIdentifier(table3) + "(c31) ON DELETE cascade ON UPDATE set null," + + " c14 int FOREIGN KEY REFERENCES " + AbstractSQLGenerator.escapeIdentifier(table4) + + "(c41) ON DELETE set null ON UPDATE cascade," + " c15 int FOREIGN KEY REFERENCES " + + AbstractSQLGenerator.escapeIdentifier(table5) + "(c51) ON DELETE set default ON UPDATE no action," + + ")"); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } @@ -77,11 +93,11 @@ public static void terminateVariation() throws SQLException { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - TestUtils.dropTableIfExists(table1, stmt); - TestUtils.dropTableIfExists(table2, stmt); - TestUtils.dropTableIfExists(table3, stmt); - TestUtils.dropTableIfExists(table4, stmt); - TestUtils.dropTableIfExists(table5, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table3), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table4), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table5), stmt); } catch (Exception e) { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java index 860ff37d63..07485bb8aa 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/databasemetadata/DatabaseMetaDataTest.java @@ -4,6 +4,7 @@ */ package com.microsoft.sqlserver.jdbc.databasemetadata; +import static org.junit.Assert.assertNotSame; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -21,6 +22,7 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -35,7 +37,6 @@ import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData; -import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.StringUtils; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; @@ -446,7 +447,7 @@ public void testGetFunctions() throws SQLException { MessageFormat form = new MessageFormat(TestResource.getResource("R_nameNull")); Object[][] msgArgs = {{"FUNCTION_CAT"}, {"FUNCTION_SCHEM"}, {"FUNCTION_NAME"}, {"NUM_INPUT_PARAMS"}, - {"NUM_OUPUT_PARAMS"}, {"NUM_RESULT_SETS"}, {"FUNCTION_TYPE"}}; + {"NUM_OUTPUT_PARAMS"}, {"NUM_RESULT_SETS"}, {"FUNCTION_TYPE"}}; while (rs.next()) { assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_CAT")), form.format(msgArgs[0])); assertTrue(!StringUtils.isEmpty(rs.getString("FUNCTION_SCHEM")), form.format(msgArgs[1])); @@ -501,4 +502,53 @@ public void testGetFunctionColumns() throws SQLException { fail(TestResource.getResource("R_unexpectedErrorMessage") + e.toString()); } } + + @Test + public void testPreparedStatementMetadataCaching() throws SQLException { + try (Connection connection = DriverManager.getConnection(connectionString)) { + + DatabaseMetaData databaseMetaData = connection.getMetaData(); + String[] types = {"TABLE"}; + + Statement stmtNullCatalog; + Statement stmtMasterCatalog; + + try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) { + stmtNullCatalog = rs.getStatement(); + } + try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) { + assertSame(stmtNullCatalog, rs.getStatement()); + rs.getStatement().close(); + } + try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) { + assertNotSame(stmtNullCatalog, rs.getStatement()); + stmtNullCatalog = rs.getStatement(); + } + try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) { + assertSame(stmtNullCatalog, rs.getStatement()); + } + try (ResultSet rs = databaseMetaData.getTables("master", null, "%", types)) { + stmtMasterCatalog = rs.getStatement(); + } + try (ResultSet rs = databaseMetaData.getTables("master", null, "%", types)) { + assertSame(stmtMasterCatalog, rs.getStatement()); + rs.getStatement().close(); + } + try (ResultSet rs = databaseMetaData.getTables("master", null, "%", types)) { + assertNotSame(stmtMasterCatalog, rs.getStatement()); + stmtMasterCatalog = rs.getStatement(); + } + try (ResultSet rs = databaseMetaData.getTables("master", null, "%", types)) { + assertSame(stmtMasterCatalog, rs.getStatement()); + } + try (ResultSet rs = databaseMetaData.getTables(null, null, "%", types)) { + assertSame(stmtNullCatalog, rs.getStatement()); + rs.getStatement().close(); + } + try (ResultSet rs = databaseMetaData.getTables("master", null, "%", types)) { + assertSame(stmtMasterCatalog, rs.getStatement()); + rs.getStatement().close(); + } + } + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java index 12f06bce03..6814627153 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/BulkCopyWithSqlVariantTest.java @@ -7,23 +7,23 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.IOException; import java.math.BigDecimal; +import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; -import java.sql.Connection; -import java.sql.ResultSet; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -34,8 +34,8 @@ @RunWith(JUnitPlatform.class) public class BulkCopyWithSqlVariantTest extends AbstractTest { - static String tableName = "sqlVariantTestSrcTable"; - static String destTableName = "sqlVariantDestTable"; + static String tableName = RandomUtil.getIdentifier("sqlVariantTestSrcTable"); + static String destTableName = RandomUtil.getIdentifier("dest_sqlVariant"); /** * Test integer value @@ -49,14 +49,16 @@ public void bulkCopyTestInt() throws SQLException { int col1Value = 5; beforeEachSetup("int", col1Value); try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getInt(1), 5); } @@ -80,13 +82,15 @@ public void bulkCopyTestSmallInt() throws SQLException { try (Statement stmt = con.createStatement()) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getShort(1), 5); } @@ -111,13 +115,15 @@ public void bulkCopyTestTinyint() throws SQLException { try (Statement stmt = con.createStatement()) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getByte(1), 5); } @@ -140,14 +146,16 @@ public void bulkCopyTestBigint() throws SQLException { beforeEachSetup("bigint", col1Value); try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getLong(1), col1Value); } @@ -171,15 +179,17 @@ public void bulkCopyTestFloat() throws SQLException { try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getDouble(1), col1Value); } @@ -202,15 +212,17 @@ public void bulkCopyTestReal() throws SQLException { try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getFloat(1), col1Value); } @@ -233,14 +245,16 @@ public void bulkCopyTestMoney() throws SQLException { try (Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getMoney(1), new BigDecimal(col1Value)); } @@ -259,23 +273,26 @@ public void bulkCopyTestSmallmoney() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { String col1Value = "126.1230"; - String destTableName = "dest_sqlVariant"; - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values (CAST (" + col1Value + " AS " + "smallmoney" + ") )"); stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "smallmoney" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + "create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + " (col1 sql_variant)"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getSmallMoney(1), new BigDecimal(col1Value)); } @@ -295,15 +312,17 @@ public void bulkCopyTestDate() throws SQLException { String col1Value = "2015-05-05"; beforeEachSetup("date", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getDate(1), col1Value); } @@ -322,23 +341,27 @@ public void bulkCopyTestTwoCols() throws SQLException { String col1Value = "2015-05-05"; String col2Value = "126.1230"; - String destTableName = "dest_sqlVariant"; - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST ('" + col1Value + "' AS " - + "date" + ")" + ",CAST (" + col2Value + " AS " + "smallmoney" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant, col2 sql_variant)"); - - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1, col2) values (CAST ('" + col1Value + "' AS " + "date" + ")" + ",CAST (" + col2Value + + " AS " + "smallmoney" + ") )"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + + " (col1 sql_variant, col2 sql_variant)"); + + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getDate(1), col1Value); assertEquals(rs.getSmallMoney(2), new BigDecimal(col2Value)); @@ -358,14 +381,16 @@ public void bulkCopyTestTimeWithScale() throws SQLException { String col1Value = "'12:26:27.1452367'"; beforeEachSetup("time(2)", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getString(1), "12:26:27.15"); // getTime does not work } @@ -386,14 +411,16 @@ public void bulkCopyTestChar() throws SQLException { beforeEachSetup("char", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getString(1).trim() + "'", col1Value); // adds space between } @@ -413,14 +440,16 @@ public void bulkCopyTestNchar() throws SQLException { String col1Value = "'a'"; beforeEachSetup("nchar", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getNString(1).trim() + "'", col1Value); } @@ -441,14 +470,16 @@ public void bulkCopyTestVarchar() throws SQLException { beforeEachSetup("varchar", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getString(1).trim() + "'", col1Value); } @@ -468,14 +499,16 @@ public void bulkCopyTestNvarchar() throws SQLException { String col1Value = "'hello'"; beforeEachSetup("nvarchar", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("'" + rs.getString(1).trim() + "'", col1Value); } @@ -495,15 +528,17 @@ public void bulkCopyTestBinary20() throws SQLException { String col1Value = "hello"; beforeEachSetup("binary(20)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } @@ -523,15 +558,17 @@ public void bulkCopyTestVarbinary20() throws SQLException { String col1Value = "hello"; beforeEachSetup("varbinary(20)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } @@ -550,14 +587,16 @@ public void bulkCopyTestVarbinary8000() throws SQLException { String col1Value = "hello"; beforeEachSetup("binary(8000)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertTrue(TestUtils.parseByte(rs.getBytes(1), col1Value.getBytes())); } @@ -576,15 +615,17 @@ public void bulkCopyTestBitNull() throws SQLException { beforeEachSetup("bit", null); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getBoolean(1), false); } @@ -603,15 +644,17 @@ public void bulkCopyTestBit() throws SQLException { int col1Value = 5000; beforeEachSetup("bit", col1Value); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getBoolean(1), true); } @@ -631,15 +674,17 @@ public void bulkCopyTestDatetime() throws SQLException { String col1Value = "2015-05-08 12:26:24.0"; beforeEachSetup("datetime", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getDateTime(1), col1Value); @@ -660,15 +705,17 @@ public void bulkCopyTestSmalldatetime() throws SQLException { String col1Value = "2015-05-08 12:26:24"; beforeEachSetup("smalldatetime", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getSmallDateTime(1), "2015-05-08 12:26:00.0"); } @@ -688,15 +735,17 @@ public void bulkCopyTestDatetime2() throws SQLException { String col1Value = "2015-05-08 12:26:24.12645"; beforeEachSetup("datetime2(2)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getTimestamp(1), "2015-05-08 12:26:24.13"); } @@ -714,22 +763,25 @@ public void bulkCopyTestTime() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { String col1Value = "'12:26:27.1452367'"; - String destTableName = "dest_sqlVariant"; - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + col1Value + " AS " + "time(2)" + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values (CAST (" + col1Value + " AS " + "time(2)" + ") )"); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + " (col1 sql_variant)"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { rs.next(); assertEquals("" + rs.getObject(1).toString(), "12:26:27"); } @@ -747,15 +799,17 @@ public void bulkCopyTestReadGUID() throws SQLException { String col1Value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; beforeEachSetup("uniqueidentifier", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals("" + rs.getUniqueIdentifier(1), col1Value); @@ -780,15 +834,17 @@ public void bulkCopyTestVarChar8000() throws SQLException { String col1Value = buffer.toString(); beforeEachSetup("varchar(8000)", "'" + col1Value + "'"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); - bulkCopy.setDestinationTableName(destTableName); + bulkCopy.setDestinationTableName(AbstractSQLGenerator.escapeIdentifier(destTableName)); bulkCopy.writeToServer(rs); bulkCopy.close(); } - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + destTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTableName))) { while (rs.next()) { assertEquals(rs.getString(1), col1Value); } @@ -799,12 +855,14 @@ public void bulkCopyTestVarChar8000() throws SQLException { private void beforeEachSetup(String colType, Object colValue) throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values (CAST (" + colValue + " AS " + colType + ") )"); stmt.executeUpdate( - "INSERT into " + tableName + "(col1) values (CAST (" + colValue + " AS " + colType + ") )"); - stmt.executeUpdate("create table " + destTableName + " (col1 sql_variant)"); + "create table " + AbstractSQLGenerator.escapeIdentifier(destTableName) + " (col1 sql_variant)"); } } @@ -817,7 +875,7 @@ private void beforeEachSetup(String colType, Object colValue) throws SQLExceptio public static void afterAll() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(destTableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java index 92b22d3574..16daac876d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/DateAndTimeTypeTest.java @@ -24,10 +24,12 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; @@ -39,6 +41,11 @@ public class DateAndTimeTypeTest extends AbstractTest { private static final Time TIME_TO_TEST = new java.sql.Time(74096000L); private static final Timestamp TIMESTAMP_TO_TEST = new java.sql.Timestamp(61494838496000L); + private String dateTVP = RandomUtil.getIdentifier("dateTVP"); + private String timeTVP = RandomUtil.getIdentifier("timeTVP"); + private String timestampTVP = RandomUtil.getIdentifier("timestampTVP"); + private static String tableName = RandomUtil.getIdentifier("DataTypesTable"); + /** * Test query with date */ @@ -46,7 +53,8 @@ public class DateAndTimeTypeTest extends AbstractTest { public void testQueryDate() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { - String sPrepStmt = "select * from dateandtime where my_date = ?"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_date = ?"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setDate(1, DATE_TO_TEST); @@ -65,7 +73,8 @@ public void testQueryDate() throws SQLException { public void testQueryTimestamp() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { - String sPrepStmt = "select * from dateandtime where my_timestamp = ?"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_timestamp = ?"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setTimestamp(1, TIMESTAMP_TO_TEST); @@ -84,7 +93,8 @@ public void testQueryTimestamp() throws SQLException { public void testQueryTime() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false")) { - String sPrepStmt = "select * from dateandtime where my_time = ?"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_time = ?"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setTime(1, TIME_TO_TEST); @@ -106,10 +116,11 @@ public void testQueryDateTVP() throws SQLException { SQLServerDataTable tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", java.sql.Types.DATE); tvp.addRow(DATE_TO_TEST); - String sPrepStmt = "select * from dateandtime where my_date IN (select * from ?)"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_date IN (select * from ?)"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection .prepareStatement(sPrepStmt)) { - pstmt.setStructured(1, "dateTVP", tvp); + pstmt.setStructured(1, dateTVP, tvp); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); @@ -129,10 +140,11 @@ public void testQueryTimestampTVP() throws SQLException { SQLServerDataTable tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", java.sql.Types.TIMESTAMP); tvp.addRow(TIMESTAMP_TO_TEST); - String sPrepStmt = "select * from dateandtime where my_timestamp IN (select * from ?)"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_timestamp IN (select * from ?)"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection .prepareStatement(sPrepStmt)) { - pstmt.setStructured(1, "timestampTVP", tvp); + pstmt.setStructured(1, timestampTVP, tvp); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); @@ -152,10 +164,11 @@ public void testQueryTimeTVP() throws SQLException { SQLServerDataTable tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", java.sql.Types.TIME); tvp.addRow(TIME_TO_TEST); - String sPrepStmt = "select * from dateandtime where my_time IN (select * from ?)"; + String sPrepStmt = "select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " where my_time IN (select * from ?)"; try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection .prepareStatement(sPrepStmt)) { - ((SQLServerPreparedStatement) pstmt).setStructured(1, "timeTVP", tvp); + ((SQLServerPreparedStatement) pstmt).setStructured(1, timeTVP, tvp); try (ResultSet rs = pstmt.executeQuery()) { rs.next(); @@ -169,9 +182,11 @@ private void createTVPs(String tvpName, String tvpType) throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName - + "') " + " drop type " + tvpName); - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 " + tvpType + " null)"; + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 " + + tvpType + " null)"; stmt.executeUpdate(TVPCreateCmd); } } @@ -186,12 +201,14 @@ public void testSetup() throws TestAbortedException, Exception { // by default to the connection. See issue https://github.com/Microsoft/mssql-jdbc/issues/559 try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists("dateandtime", stmt); - String sql1 = "create table dateandtime (id integer not null, my_date date, my_time time, my_timestamp datetime2 constraint pk_esimple primary key (id))"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id integer not null, my_date date, my_time time, my_timestamp datetime2 constraint pk_esimple primary key (id))"; stmt.execute(sql1); // add one sample data - String sPrepStmt = "insert into dateandtime (id, my_date, my_time, my_timestamp) values (?, ?, ?, ?)"; + String sPrepStmt = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id, my_date, my_time, my_timestamp) values (?, ?, ?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(sPrepStmt)) { pstmt.setInt(1, 42); pstmt.setDate(2, DATE_TO_TEST); @@ -199,9 +216,9 @@ public void testSetup() throws TestAbortedException, Exception { pstmt.setTimestamp(4, TIMESTAMP_TO_TEST); pstmt.execute(); pstmt.close(); - createTVPs("dateTVP", "date"); - createTVPs("timeTVP", "time"); - createTVPs("timestampTVP", "datetime2"); + createTVPs(dateTVP, "date"); + createTVPs(timeTVP, "time"); + createTVPs(timestampTVP, "datetime2"); } } } @@ -210,7 +227,7 @@ public void testSetup() throws TestAbortedException, Exception { public static void terminateVariation() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString + ";sendTimeAsDatetime=false"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists("dateandtime", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java index 040793ed91..6a95f29c9e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLServerSpatialDatatypeTest.java @@ -7,12 +7,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; +import java.sql.Connection; import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; -import java.sql.Connection; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; @@ -25,12 +25,14 @@ import com.microsoft.sqlserver.jdbc.Geography; import com.microsoft.sqlserver.jdbc.Geometry; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -41,9 +43,9 @@ @RunWith(JUnitPlatform.class) public class SQLServerSpatialDatatypeTest extends AbstractTest { - static String geomTableName = "geometryTestTable"; - static String geogTableName = "geographyTestTable"; - static String spatialDatatypeTableName = "spatialDatatypeTestTable"; + static String geomTableName; + static String geogTableName; + static String spatialDatatypeTableName; static boolean isDenaliOrLater = false; @Test @@ -315,13 +317,13 @@ public void testFullGlobeWkt() throws SQLException { assertEquals(e.getMessage(), "Fullglobe is not supported for Geometry."); } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKT); } @@ -479,8 +481,8 @@ public void testAllTypes() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)")) { geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); pstmt.setGeometry(1, geomWKT); pstmt.executeUpdate(); @@ -522,7 +524,7 @@ public void testAllTypes() throws SQLException { pstmt.executeUpdate(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); @@ -531,8 +533,8 @@ public void testAllTypes() throws SQLException { } // Geography - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)")) { geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); pstmt.setGeography(1, geogWKT); @@ -584,7 +586,7 @@ public void testAllTypes() throws SQLException { pstmt.executeUpdate(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKTList.get(i)); @@ -633,8 +635,9 @@ public void testMixedAllTypes() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) + + " values (?, ?, ?, ?, ?)");) { geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); pstmt.setGeometry(1, geomWKT); @@ -735,8 +738,8 @@ public void testMixedAllTypes() throws SQLException { pstmt.executeUpdate(); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select * from " + spatialDatatypeTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTList.get(i)); @@ -773,26 +776,26 @@ public void testParse() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); assertEquals(rs.getGeometry(1).getSrid(), 0); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKT); assertEquals(rs.getGeography(1).getSrid(), 4326); @@ -814,26 +817,26 @@ public void testPoint() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKT); assertEquals(rs.getGeometry(1).getSrid(), 0); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKT); assertEquals(rs.getGeography(1).getSrid(), 4326); @@ -855,25 +858,25 @@ public void testSTAsText() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).STAsText(), geoWKTSS); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).STAsText(), geoWKTSS); } @@ -909,8 +912,8 @@ public void testCheckGeomMetaData() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + geomTableName + " (c1) VALUES (?)")) { + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); Geometry g = Geometry.STGeomFromText("POINT (1 2 3 4)", 0); pstmt.setGeometry(1, g); @@ -920,7 +923,8 @@ public void testCheckGeomMetaData() throws SQLException { String sqlTypeName = paramMetaData.getParameterTypeName(1); assertEquals(sqlType, -157); assertEquals(sqlTypeName, "geometry"); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geomTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { ResultSetMetaData rsmd = rs.getMetaData(); assertEquals(rsmd.getColumnType(1), -157); } @@ -933,8 +937,8 @@ public void testCheckGeogMetaData() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + geogTableName + " (c1) VALUES (?)")) { + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " (c1) VALUES (?)")) { ParameterMetaData paramMetaData = pstmt.getParameterMetaData(); Geography g = Geography.STGeomFromText("POINT (1 2 3 4)", 4326); pstmt.setGeography(1, g); @@ -944,7 +948,8 @@ public void testCheckGeogMetaData() throws SQLException { String sqlTypeName = paramMetaData.getParameterTypeName(1); assertEquals(sqlType, -158); assertEquals(sqlTypeName, "geography"); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + geogTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { ResultSetMetaData rsmd = rs.getMetaData(); assertEquals(rsmd.getColumnType(1), -158); } @@ -998,8 +1003,9 @@ public void testNull() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + spatialDatatypeTableName + " values (?, ?, ?, ?, ?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) + + " values (?, ?, ?, ?, ?)");) { geomWKT = Geometry.STGeomFromText(geoWKTPoint, 0); geogWKT = Geography.STGeomFromText(geoWKTPoint, 4326); pstmt.setGeometry(1, geomWKT); @@ -1020,8 +1026,8 @@ public void testNull() throws SQLException { pstmt.executeUpdate(); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select * from " + spatialDatatypeTableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName))) { for (int i = 0; i < geoWKTList.size(); i++) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTListExpected.get(i)); @@ -1039,19 +1045,21 @@ public void testNull() throws SQLException { private void beforeEachSetup() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists(geomTableName, stmt); - TestUtils.dropTableIfExists(geogTableName, stmt); - stmt.executeUpdate("Create table " + geomTableName + " (c1 geometry)"); - stmt.executeUpdate("Create table " + geogTableName + " (c1 geography)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geomTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geogTableName), stmt); + stmt.executeUpdate( + "Create table " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " (c1 geometry)"); + stmt.executeUpdate( + "Create table " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " (c1 geography)"); } } private void beforeEachSetupSpatialDatatype() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists(spatialDatatypeTableName, stmt); - stmt.executeUpdate("Create table " + spatialDatatypeTableName + " (c1 geometry," + "c2 geography," - + "c3 nvarchar(512)," + "c4 decimal(28,4)," + "c5 int)"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName), stmt); + stmt.executeUpdate("Create table " + AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName) + + " (c1 geometry," + "c2 geography," + "c3 nvarchar(512)," + "c4 decimal(28,4)," + "c5 int)"); } } @@ -1066,25 +1074,25 @@ private void testWkt(String geoWKT, String geoWKTSS) throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geomTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geomTableName) + " values (?)");) { pstmt.setGeometry(1, geomWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geomTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geomTableName))) { rs.next(); assertEquals(rs.getGeometry(1).asTextZM(), geoWKTSS); } } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + geogTableName + " values (?)");) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(geogTableName) + " values (?)");) { pstmt.setGeography(1, geogWKT); pstmt.execute(); try (SQLServerResultSet rs = (SQLServerResultSet) stmt - .executeQuery("select c1 from " + geogTableName)) { + .executeQuery("select c1 from " + AbstractSQLGenerator.escapeIdentifier(geogTableName))) { rs.next(); assertEquals(rs.getGeography(1).asTextZM(), geoWKTSS); } @@ -1111,6 +1119,10 @@ private static byte[] hexStringToByteArray(String s) { */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { + geomTableName = RandomUtil.getIdentifier("geometryTestTable"); + geogTableName = RandomUtil.getIdentifier("geographyTestTable"); + spatialDatatypeTableName = RandomUtil.getIdentifier("spatialDatatypeTestTable"); + try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt .executeQuery("select SERVERPROPERTY ( 'ProductVersion' )")) { @@ -1139,8 +1151,9 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti public static void afterAll() throws SQLException { try (Connection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists(geomTableName, stmt); - TestUtils.dropTableIfExists(geogTableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geomTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(geogTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(spatialDatatypeTableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java index cfb5729b4f..babee66d8e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/SQLVariantResultSetTest.java @@ -24,12 +24,14 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -40,12 +42,8 @@ @RunWith(JUnitPlatform.class) public class SQLVariantResultSetTest extends AbstractTest { - static SQLServerConnection con = null; - static Statement stmt = null; - static String tableName = "sqlVariantTestSrcTable"; - static String inputProc = "sqlVariantProc"; - static SQLServerResultSet rs = null; - static SQLServerPreparedStatement pstmt = null; + static String tableName; + static String inputProc; /** * Read int value @@ -56,11 +54,17 @@ public class SQLVariantResultSetTest extends AbstractTest { */ @Test public void readInt() throws SQLException, SecurityException, IOException { - int value = 2; - createAndPopulateTable("int", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + + int value = 2; + createAndPopulateTable("int", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + value); + } + } } /** @@ -71,11 +75,16 @@ public void readInt() throws SQLException, SecurityException, IOException { */ @Test public void readMoney() throws SQLException { - Double value = 123.12; - createAndPopulateTable("Money", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + Double value = 123.12; + createAndPopulateTable("Money", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + } + } } /** @@ -85,11 +94,16 @@ public void readMoney() throws SQLException { */ @Test public void readSmallMoney() throws SQLException { - Double value = 123.12; - createAndPopulateTable("smallmoney", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + Double value = 123.12; + createAndPopulateTable("smallmoney", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), new BigDecimal("123.1200")); + } + } } /** @@ -99,11 +113,16 @@ public void readSmallMoney() throws SQLException { */ @Test public void readGUID() throws SQLException { - String value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; - createAndPopulateTable("uniqueidentifier", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getUniqueIdentifier(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "1AE740A2-2272-4B0F-8086-3DDAC595BC11"; + createAndPopulateTable("uniqueidentifier", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getUniqueIdentifier(1), value); + } + } } /** @@ -113,11 +132,16 @@ public void readGUID() throws SQLException { */ @Test public void readDate() throws SQLException { - String value = "'2015-05-08'"; - createAndPopulateTable("date", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1), "2015-05-08"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'2015-05-08'"; + createAndPopulateTable("date", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1), "2015-05-08"); + } + } } /** @@ -127,11 +151,16 @@ public void readDate() throws SQLException { */ @Test public void readTime() throws SQLException { - String value = "'12:26:27.123345'"; - createAndPopulateTable("time(3)", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1).toString(), "12:26:27"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'12:26:27.123345'"; + createAndPopulateTable("time(3)", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1).toString(), "12:26:27"); + } + } } /** @@ -141,11 +170,16 @@ public void readTime() throws SQLException { */ @Test public void readDateTime() throws SQLException { - String value = "'2015-05-08 12:26:24'"; - createAndPopulateTable("datetime", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1), "2015-05-08 12:26:24.0"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'2015-05-08 12:26:24'"; + createAndPopulateTable("datetime", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1), "2015-05-08 12:26:24.0"); + } + } } /** @@ -155,11 +189,16 @@ public void readDateTime() throws SQLException { */ @Test public void readSmallDateTime() throws SQLException { - String value = "'2015-05-08 12:26:24'"; - createAndPopulateTable("smalldatetime", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals("" + rs.getObject(1), "2015-05-08 12:26:00.0"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "'2015-05-08 12:26:24'"; + createAndPopulateTable("smalldatetime", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals("" + rs.getObject(1), "2015-05-08 12:26:00.0"); + } + } } /** @@ -175,9 +214,12 @@ public void readVarChar8000() throws SQLException { } String value = "'" + buffer.toString() + "'"; createAndPopulateTable("VARCHAR(8000)", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), buffer.toString()); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), buffer.toString()); + } } /** @@ -187,11 +229,16 @@ public void readVarChar8000() throws SQLException { */ @Test public void readFloat() throws SQLException { - float value = 5; - createAndPopulateTable("float", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), Double.valueOf("5.0")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + float value = 5; + createAndPopulateTable("float", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), Double.valueOf("5.0")); + } + } } /** @@ -201,11 +248,16 @@ public void readFloat() throws SQLException { */ @Test public void readBigInt() throws SQLException { - long value = 5; - createAndPopulateTable("bigint", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + long value = 5; + createAndPopulateTable("bigint", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -215,11 +267,16 @@ public void readBigInt() throws SQLException { */ @Test public void readSmallInt() throws SQLException { - short value = 5; - createAndPopulateTable("smallint", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + short value = 5; + createAndPopulateTable("smallint", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -229,11 +286,16 @@ public void readSmallInt() throws SQLException { */ @Test public void readTinyInt() throws SQLException { - short value = 5; - createAndPopulateTable("tinyint", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + short value = 5; + createAndPopulateTable("tinyint", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -243,11 +305,16 @@ public void readTinyInt() throws SQLException { */ @Test public void readBit() throws SQLException { - int value = 50000; - createAndPopulateTable("bit", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), true); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int value = 50000; + createAndPopulateTable("bit", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), true); + } + } } /** @@ -257,11 +324,16 @@ public void readBit() throws SQLException { */ @Test public void readReal() throws SQLException { - float value = 5; - createAndPopulateTable("Real", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), Float.valueOf("5.0")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + float value = 5; + createAndPopulateTable("Real", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), Float.valueOf("5.0")); + } + } } /** @@ -271,11 +343,16 @@ public void readReal() throws SQLException { */ @Test public void readNChar() throws SQLException, SecurityException, IOException { - String value = "a"; - createAndPopulateTable("nchar(5)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getNString(1).trim(), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "a"; + createAndPopulateTable("nchar(5)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getNString(1).trim(), value); + } + } } /** @@ -287,11 +364,16 @@ public void readNChar() throws SQLException, SecurityException, IOException { */ @Test public void readNVarChar() throws SQLException, SecurityException, IOException { - String value = "nvarchar"; - createAndPopulateTable("nvarchar(10)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "nvarchar"; + createAndPopulateTable("nvarchar(10)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value); + } + } } /** @@ -303,11 +385,16 @@ public void readNVarChar() throws SQLException, SecurityException, IOException { */ @Test public void readBinary20() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(20)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(20)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -319,11 +406,16 @@ public void readBinary20() throws SQLException, SecurityException, IOException { */ @Test public void readVarBinary20() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("varbinary(20)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("varbinary(20)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -335,11 +427,16 @@ public void readVarBinary20() throws SQLException, SecurityException, IOExceptio */ @Test public void readBinary512() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(512)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(512)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -351,11 +448,16 @@ public void readBinary512() throws SQLException, SecurityException, IOException */ @Test public void readBinary8000() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(8000)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(8000)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -367,11 +469,16 @@ public void readBinary8000() throws SQLException, SecurityException, IOException */ @Test public void readvarBinary8000() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("varbinary(8000)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("varbinary(8000)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + } + } } /** @@ -383,14 +490,18 @@ public void readvarBinary8000() throws SQLException, SecurityException, IOExcept */ @Test public void readSQLVariantProperty() throws SQLException, SecurityException, IOException { - String value = "hi"; - createAndPopulateTable("binary(8000)", "'" + value + "'"); - rs = (SQLServerResultSet) stmt.executeQuery( - "SELECT SQL_VARIANT_PROPERTY(col1,'BaseType') AS 'Base Type', SQL_VARIANT_PROPERTY(col1,'Precision') AS 'Precision' from " - + tableName); - rs.next(); - assertTrue(rs.getString(1).equalsIgnoreCase("binary"), - "unexpected baseType, expected: binary, retrieved:" + rs.getString(1)); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "hi"; + createAndPopulateTable("binary(8000)", "'" + value + "'"); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "SELECT SQL_VARIANT_PROPERTY(col1,'BaseType') AS 'Base Type', SQL_VARIANT_PROPERTY(col1,'Precision') AS 'Precision' from " + + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(rs.getString(1).equalsIgnoreCase("binary"), + "unexpected baseType, expected: binary, retrieved:" + rs.getString(1)); + } + } } /** @@ -404,15 +515,20 @@ public void insertVarChar8001() throws SQLException { for (int i = 0; i < 8001; i++) { buffer.append("a"); } - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + tableName + " values (?)"); - pstmt.setObject(1, buffer.toString()); - try { - pstmt.execute(); - } catch (SQLServerException e) { - assertTrue(e.toString().contains("com.microsoft.sqlserver.jdbc.SQLServerException: Operand type clash")); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?)"); + pstmt.setObject(1, buffer.toString()); + try { + pstmt.execute(); + } catch (SQLServerException e) { + assertTrue( + e.toString().contains("com.microsoft.sqlserver.jdbc.SQLServerException: Operand type clash")); + } } } @@ -429,9 +545,14 @@ public void readNvarChar4000() throws SQLException { } String value = "'" + buffer.toString() + "'"; createAndPopulateTable("NVARCHAR(4000)", value); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), buffer.toString()); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), buffer.toString()); + } + } } /** @@ -443,20 +564,23 @@ public void readNvarChar4000() throws SQLException { */ @Test public void UpdateInt() throws SQLException, SecurityException, IOException { - int value = 2; - int updatedValue = 3; - createAndPopulateTable("int", value); - stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + value); - rs.updateInt(1, updatedValue); - rs.updateRow(); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + updatedValue); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + int value = 2; + int updatedValue = 3; + createAndPopulateTable("int", value); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + value); + rs.updateInt(1, updatedValue); + rs.updateRow(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + updatedValue); + } } } @@ -469,21 +593,25 @@ public void UpdateInt() throws SQLException, SecurityException, IOException { */ @Test public void UpdateNChar() throws SQLException, SecurityException, IOException { - String value = "a"; - String updatedValue = "b"; - - createAndPopulateTable("nchar", "'" + value + "'"); - stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1).trim(), "" + value); - rs.updateNString(1, updatedValue); - rs.updateRow(); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getString(1), "" + updatedValue); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + String value = "a"; + String updatedValue = "b"; + + createAndPopulateTable("nchar", "'" + value + "'"); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1).trim(), "" + value); + rs.updateNString(1, updatedValue); + rs.updateRow(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getString(1), "" + updatedValue); + } } } @@ -496,20 +624,24 @@ public void UpdateNChar() throws SQLException, SecurityException, IOException { */ @Test public void updateBinary20() throws SQLException, SecurityException, IOException { - String value = "hi"; - String updatedValue = "bye"; - createAndPopulateTable("binary(20)", "'" + value + "'"); - stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); - rs.updateBytes(1, updatedValue.getBytes()); - rs.updateRow(); - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertTrue(parseByte((byte[]) rs.getBytes(1), updatedValue.getBytes())); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + String value = "hi"; + String updatedValue = "bye"; + createAndPopulateTable("binary(20)", "'" + value + "'"); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getObject(1), (byte[]) value.getBytes())); + rs.updateBytes(1, updatedValue.getBytes()); + rs.updateRow(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertTrue(parseByte((byte[]) rs.getBytes(1), updatedValue.getBytes())); + } } } @@ -520,28 +652,34 @@ public void updateBinary20() throws SQLException, SecurityException, IOException */ @Test public void insertTest() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 int)"); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con - .prepareStatement("insert into " + tableName + " values (?, ?)"); - - String[] col1Value = {"Hello", null}; - int[] col2Value = {1, 2}; - pstmt.setObject(1, "Hello"); - pstmt.setInt(2, 1); - pstmt.execute(); - pstmt.setObject(1, null); - pstmt.setInt(2, 2); - pstmt.execute(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - int i = 0; - rs.next(); - do { - assertEquals(rs.getObject(1), col1Value[i]); - assertEquals(rs.getObject(2), col2Value[i]); - i++; - } while (rs.next()); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 int)"); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?, ?)"); + + String[] col1Value = {"Hello", null}; + int[] col2Value = {1, 2}; + pstmt.setObject(1, "Hello"); + pstmt.setInt(2, 1); + pstmt.execute(); + pstmt.setObject(1, null); + pstmt.setInt(2, 2); + pstmt.execute(); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + int i = 0; + rs.next(); + do { + assertEquals(rs.getObject(1), col1Value[i]); + assertEquals(rs.getObject(2), col2Value[i]); + i++; + } while (rs.next()); + } + } } /** @@ -551,16 +689,23 @@ public void insertTest() throws SQLException { */ @Test public void insertTestNull() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values ( ?)"); - - pstmt.setObject(1, null); - pstmt.execute(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getBoolean(1), false); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values ( ?)")) { + + pstmt.setObject(1, null); + pstmt.execute(); + } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getBoolean(1), false); + } + } } /** @@ -571,16 +716,24 @@ public void insertTestNull() throws SQLException { */ @Test public void insertSetObject() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values (?)"); - - pstmt.setObject(1, 2); - pstmt.execute(); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), 2); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?)")) { + + pstmt.setObject(1, 2); + pstmt.execute(); + } + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), 2); + } + } } /** @@ -590,22 +743,29 @@ public void insertSetObject() throws SQLException { */ @Test public void callableStatementOutputIntTest() throws SQLException { - int value = 5; - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value + " AS " + "int" + "))"); - - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " - + tableName; - stmt.execute(sql); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getString(1), String.valueOf(value)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int value = 5; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST (" + + value + " AS " + "int" + "))"); + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName); + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getString(1), String.valueOf(value)); + if (null != cs) { + cs.close(); + } } } @@ -616,23 +776,30 @@ public void callableStatementOutputIntTest() throws SQLException { */ @Test public void callableStatementOutputDateTest() throws SQLException { - String value = "2015-05-08"; - - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST ('" + value + "' AS " + "date" + "))"); - - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " - + tableName; - stmt.execute(sql); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getString(1), String.valueOf(value)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "2015-05-08"; + + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST ('" + + value + "' AS " + "date" + "))"); + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName); + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getString(1), String.valueOf(value)); + if (null != cs) { + cs.close(); + } } } @@ -643,23 +810,30 @@ public void callableStatementOutputDateTest() throws SQLException { */ @Test public void callableStatementOutputTimeTest() throws SQLException { - String value = "12:26:27.123345"; - String returnValue = "12:26:27"; - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST ('" + value + "' AS " + "time(3)" + "))"); - - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " - + tableName; - stmt.execute(sql); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT, 3); - cs.execute(); - assertEquals(String.valueOf(returnValue), "" + cs.getObject(1)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String value = "12:26:27.123345"; + String returnValue = "12:26:27"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST ('" + + value + "' AS " + "time(3)" + "))"); + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT AS SELECT TOP 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName); + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT, 3); + cs.execute(); + assertEquals(String.valueOf(returnValue), "" + cs.getObject(1)); + if (null != cs) { + cs.close(); + } } } @@ -670,27 +844,36 @@ public void callableStatementOutputTimeTest() throws SQLException { */ @Test public void callableStatementOutputBinaryTest() throws SQLException { - byte[] binary20 = RandomData.generateBinaryTypes("20", false, false); - byte[] secondBinary20 = RandomData.generateBinaryTypes("20", false, false); - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); - pstmt = (SQLServerPreparedStatement) con.prepareStatement("insert into " + tableName + " values (?,?)"); - pstmt.setObject(1, binary20); - pstmt.setObject(2, secondBinary20); - pstmt.execute(); - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" - + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1 "; - stmt.execute(sql); - - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?,?) }"); - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(2, secondBinary20, microsoft.sql.Types.SQL_VARIANT); - - cs.execute(); - assertTrue(parseByte((byte[]) cs.getBytes(1), binary20)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + byte[] binary20 = RandomData.generateBinaryTypes("20", false, false); + byte[] secondBinary20 = RandomData.generateBinaryTypes("20", false, false); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant)"); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?,?)")) { + pstmt.setObject(1, binary20); + pstmt.setObject(2, secondBinary20); + pstmt.execute(); + } + + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1 "; + stmt.execute(sql); + + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(2, secondBinary20, microsoft.sql.Types.SQL_VARIANT); + + cs.execute(); + assertTrue(parseByte((byte[]) cs.getBytes(1), binary20)); + if (null != cs) { + cs.close(); + } } } @@ -701,24 +884,30 @@ public void callableStatementOutputBinaryTest() throws SQLException { */ @Test public void callableStatementInputOutputIntTest() throws SQLException { - int col1Value = 5; - int col2Value = 2; - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 int)"); - stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" - + "), " + col2Value + ")"); - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" - + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1"; - stmt.execute(sql); - CallableStatement cs = con.prepareCall(" {call " + inputProc + " (?,?) }"); - - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(2, col2Value, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getObject(1), col1Value); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int col1Value = 5; + int col2Value = 2; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 int)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" + "), " + col2Value + ")"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1"; + stmt.execute(sql); + CallableStatement cs = con + .prepareCall(" {call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(2, col2Value, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getObject(1), col1Value); + if (null != cs) { + cs.close(); + } } } @@ -729,27 +918,33 @@ public void callableStatementInputOutputIntTest() throws SQLException { */ @Test public void callableStatementInputOutputReturnIntTest() throws SQLException { - int col1Value = 5; - int col2Value = 2; - int returnValue = 12; - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 int)"); - stmt.executeUpdate("INSERT into " + tableName + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" - + "), " + col2Value + ")"); - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" - + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1" + " return " + returnValue; - stmt.execute(sql); - CallableStatement cs = con.prepareCall(" {? = call " + inputProc + " (?,?) }"); - - cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); - cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); - cs.execute(); - assertEquals(cs.getString(1), String.valueOf(returnValue)); - assertEquals(cs.getString(2), String.valueOf(col1Value)); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + int col1Value = 5; + int col2Value = 2; + int returnValue = 12; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 int)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1, col2) values (CAST (" + col1Value + " AS " + "int" + "), " + col2Value + ")"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1" + " return " + returnValue; + stmt.execute(sql); + CallableStatement cs = con + .prepareCall(" {? = call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + + cs.registerOutParameter(1, microsoft.sql.Types.SQL_VARIANT); + cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); + cs.execute(); + assertEquals(cs.getString(1), String.valueOf(returnValue)); + assertEquals(cs.getString(2), String.valueOf(col1Value)); + if (null != cs) { + cs.close(); + } } } @@ -760,28 +955,35 @@ public void callableStatementInputOutputReturnIntTest() throws SQLException { */ @Test public void callableStatementInputOutputReturnStringTest() throws SQLException { - String col1Value = "aa"; - String col2Value = "bb"; - int returnValue = 12; - - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + "(col1,col2) values" + " (CAST ('" + col1Value + "' AS " - + "varchar(5)" + ")" + " ,CAST ('" + col2Value + "' AS " + "varchar(5)" + ")" + ")"); - TestUtils.dropProcedureIfExists(inputProc, stmt); - String sql = "CREATE PROCEDURE " + inputProc + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" - + " SELECT top 1 @p0=col1 FROM " + tableName + " where col2=@p1 " + " return " + returnValue; - stmt.execute(sql); - CallableStatement cs = con.prepareCall(" {? = call " + inputProc + " (?,?) }"); - cs.registerOutParameter(1, java.sql.Types.INTEGER); - cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); - cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); - - cs.execute(); - assertEquals(returnValue, cs.getObject(1)); - assertEquals(cs.getObject(2), col1Value); - if (null != cs) { - cs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + String col1Value = "aa"; + String col2Value = "bb"; + int returnValue = 12; + + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(col1,col2) values" + + " (CAST ('" + col1Value + "' AS " + "varchar(5)" + ")" + " ,CAST ('" + col2Value + "' AS " + + "varchar(5)" + ")" + ")"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(inputProc) + + " @p0 sql_variant OUTPUT, @p1 sql_variant" + " AS" + " SELECT top 1 @p0=col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col2=@p1 " + " return " + returnValue; + stmt.execute(sql); + CallableStatement cs = con + .prepareCall(" {? = call " + AbstractSQLGenerator.escapeIdentifier(inputProc) + " (?,?) }"); + cs.registerOutParameter(1, java.sql.Types.INTEGER); + cs.registerOutParameter(2, microsoft.sql.Types.SQL_VARIANT); + cs.setObject(3, col2Value, microsoft.sql.Types.SQL_VARIANT); + + cs.execute(); + assertEquals(returnValue, cs.getObject(1)); + assertEquals(cs.getObject(2), col1Value); + if (null != cs) { + cs.close(); + } } } @@ -792,23 +994,26 @@ public void callableStatementInputOutputReturnStringTest() throws SQLException { */ @Test public void readSeveralRows() throws SQLException { - short value1 = 5; - int value2 = 10; - String value3 = "hi"; - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant, col2 sql_variant, col3 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value1 + " AS " + "tinyint" + ")" - + ",CAST (" + value2 + " AS " + "int" + ")" + ",CAST ('" + value3 + "' AS " + "char(2)" + ")" + ")"); - - rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName); - rs.next(); - assertEquals(rs.getObject(1), value1); - assertEquals(rs.getObject(2), value2); - assertEquals(rs.getObject(3), value3); - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + short value1 = 5; + int value2 = 10; + String value3 = "hi"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 sql_variant, col2 sql_variant, col3 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST (" + + value1 + " AS " + "tinyint" + ")" + ",CAST (" + value2 + " AS " + "int" + ")" + ",CAST ('" + + value3 + "' AS " + "char(2)" + ")" + ")"); + + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { + rs.next(); + assertEquals(rs.getObject(1), value1); + assertEquals(rs.getObject(2), value2); + assertEquals(rs.getObject(3), value3); + } } - } /** @@ -818,12 +1023,16 @@ public void readSeveralRows() throws SQLException { */ @Test public void readVarcharInteger() throws SQLException { - Object expected[] = {"abc", 42}; - int index = 0; - rs = (SQLServerResultSet) stmt - .executeQuery("SELECT cast('abc' as sql_variant) UNION ALL SELECT cast(42 as sql_variant)"); - while (rs.next()) { - assertEquals(rs.getObject(1), expected[index++]); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + Object expected[] = {"abc", 42}; + int index = 0; + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT cast('abc' as sql_variant) UNION ALL SELECT cast(42 as sql_variant)")) { + while (rs.next()) { + assertEquals(rs.getObject(1), expected[index++]); + } + } } } @@ -834,17 +1043,19 @@ public void readVarcharInteger() throws SQLException { */ @Test public void testUnsupportedDatatype() throws SQLException { - rs = (SQLServerResultSet) stmt - .executeQuery("select cast(cast('2017-08-16 17:31:09.995 +07:00' as datetimeoffset) as sql_variant)"); - rs.next(); - try { - rs.getObject(1); - fail(TestResource.getResource("R_expectedExceptionNotThrown")); - } catch (Exception e) { - assertTrue(e.getMessage().equalsIgnoreCase("Unexpected TDS type DATETIMEOFFSETN in SQL_VARIANT.")); - } - if (null != rs) { - rs.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery( + "select cast(cast('2017-08-16 17:31:09.995 +07:00' as datetimeoffset) as sql_variant)")) { + rs.next(); + try { + rs.getObject(1); + fail(TestResource.getResource("R_expectedExceptionNotThrown")); + } catch (Exception e) { + assertTrue( + e.getMessage().equalsIgnoreCase("Unexpected TDS type DATETIMEOFFSETN in SQL_VARIANT.")); + } + } } } @@ -856,10 +1067,13 @@ public void testUnsupportedDatatype() throws SQLException { */ @Test public void testTimeClassAsSqlVariant() throws SQLException { - rs = (SQLServerResultSet) stmt.executeQuery("select cast(cast('17:31:09.995' as time(3)) as sql_variant)"); - rs.next(); - Object object = rs.getObject(1); - assertEquals(object.getClass(), java.sql.Time.class);; + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement(); SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select cast(cast('17:31:09.995' as time(3)) as sql_variant)")) { + rs.next(); + Object object = rs.getObject(1); + assertEquals(object.getClass(), java.sql.Time.class);; + } } private boolean parseByte(byte[] expectedData, byte[] retrieved) { @@ -879,9 +1093,14 @@ private boolean parseByte(byte[] expectedData, byte[] retrieved) { * @throws SQLException */ private void createAndPopulateTable(String columnType, Object value) throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("create table " + tableName + " (col1 sql_variant)"); - stmt.executeUpdate("INSERT into " + tableName + " values (CAST (" + value + " AS " + columnType + "))"); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 sql_variant)"); + stmt.executeUpdate("INSERT into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (CAST (" + + value + " AS " + columnType + "))"); + } } /** @@ -893,8 +1112,8 @@ private void createAndPopulateTable(String columnType, Object value) throws SQLE */ @BeforeAll public static void setupHere() throws SQLException, SecurityException, IOException { - con = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = con.createStatement(); + tableName = RandomUtil.getIdentifier("sqlVariantTestSrcTable"); + inputProc = RandomUtil.getIdentifier("sqlVariantProc"); } /** @@ -904,24 +1123,10 @@ public static void setupHere() throws SQLException, SecurityException, IOExcepti */ @AfterAll public static void afterAll() throws SQLException { - TestUtils.dropProcedureIfExists(inputProc, stmt); - TestUtils.dropTableIfExists(tableName, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != pstmt) { - pstmt.close(); - } - - if (null != rs) { - rs.close(); - } - - if (null != con) { - con.close(); + try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = con.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(inputProc), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java index 6d35691d9e..d58c5dd15a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -22,6 +22,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.RandomData; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; @@ -30,6 +31,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.sqlType.SqlDate; @@ -40,9 +42,10 @@ public class TVPWithSqlVariantTest extends AbstractTest { private static SQLServerConnection conn = null; static SQLServerStatement stmt = null; static SQLServerDataTable tvp = null; - private static String tvpName = "numericTVP"; - private static String destTable = "destTvpSqlVariantTable"; - private static String procedureName = "procedureThatCallsTVP"; + + private static String tvpName = RandomUtil.getIdentifier("numericTVP"); + private static String destTable = RandomUtil.getIdentifier("destTvpSqlVariantTable"); + private static String procedureName = RandomUtil.getIdentifier("procedureThatCallsTVP"); /** * Test a previous failure regarding to numeric precision. Issue #211 @@ -56,13 +59,14 @@ public void testInt() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(12); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getInt(1), 12); assertEquals(rs.getString(1), "" + 12); @@ -84,13 +88,14 @@ public void testDate() throws SQLException { tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(date); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), "" + date); // TODO: GetDate has issues } @@ -109,13 +114,14 @@ public void testMoney() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(new BigDecimal(numeric[14])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getMoney(1), new BigDecimal(numeric[14])); } @@ -134,14 +140,15 @@ public void testSmallInt() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Short.valueOf(numeric[2])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals("" + rs.getInt(1), numeric[2]); // System.out.println(rs.getShort(1)); //does not work says cannot cast integer to short cause it is @@ -164,12 +171,13 @@ public void testBigInt() throws SQLException { String[] numeric = createNumericValues(); tvp.addRow(Long.parseLong(numeric[4])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getLong(1), Long.parseLong(numeric[4])); } @@ -188,12 +196,13 @@ public void testBoolean() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Boolean.parseBoolean(numeric[0])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getBoolean(1), Boolean.parseBoolean(numeric[0])); } @@ -212,12 +221,13 @@ public void testFloat() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String[] numeric = createNumericValues(); tvp.addRow(Float.parseFloat(numeric[1])); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getFloat(1), Float.parseFloat(numeric[1])); } @@ -236,12 +246,13 @@ public void testNvarChar() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); String colValue = "س"; tvp.addRow(colValue); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), colValue); } @@ -265,12 +276,13 @@ public void testVarChar8000() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -294,8 +306,8 @@ public void testLongVarChar() throws SQLException { String value = buffer.toString(); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); try { pstmt.execute(); @@ -322,12 +334,13 @@ public void testDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(timestamp); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { while (rs.next()) { assertEquals(rs.getString(1), "" + timestamp); // System.out.println(rs.getDateTime(1));// TODO does not work @@ -351,15 +364,14 @@ public void testNull() throws SQLException { assertTrue(e.getMessage().startsWith("Use of TVPs containing null sql_variant columns is not supported.")); } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + destTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(destTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); } - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + destTable)) { - while (rs.next()) { - System.out.println(rs.getString(1)); - } + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(destTable))) { + while (rs.next()) {} } } @@ -372,19 +384,16 @@ public void testNull() throws SQLException { @Test public void testIntStoredProcedure() throws SQLException { java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0"); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; tvp = new SQLServerDataTable(); tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); tvp.addRow(timestamp); - SQLServerCallableStatement Cstatement = (SQLServerCallableStatement) conn.prepareCall(sql); - Cstatement.setStructured(1, tvpName, tvp); - Cstatement.execute(); - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + destTable)) { - while (rs.next()) { - System.out.println(rs.getString(1)); - } - if (null != Cstatement) { - Cstatement.close(); + try (SQLServerCallableStatement cstatement = (SQLServerCallableStatement) conn.prepareCall(sql)) { + cstatement.setStructured(1, tvpName, tvp); + cstatement.execute(); + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(destTable))) { + while (rs.next()) {} } } } @@ -459,8 +468,8 @@ public void testSetup() throws SQLException { .getConnection(connectionString + ";sendStringParametersAsUnicode=true;"); stmt = (SQLServerStatement) conn.createStatement(); - TestUtils.dropProcedureIfExists(procedureName, stmt); - TestUtils.dropTableIfExists(destTable, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); dropTVPS(); createTVPS(); @@ -469,31 +478,34 @@ public void testSetup() throws SQLException { } private static void dropTVPS() throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); } private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + destTable + " SELECT * FROM @InputData" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(destTable) + " SELECT * FROM @InputData" + " END"; stmt.execute(sql); } private void createTables() throws SQLException { - String sql = "create table " + destTable + " (c1 sql_variant null);"; + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(destTable) + " (c1 sql_variant null);"; stmt.execute(sql); } private void createTVPS() throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 sql_variant null)"; + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + + " as table (c1 sql_variant null)"; stmt.executeUpdate(TVPCreateCmd); } @AfterEach public void terminateVariation() throws SQLException { - TestUtils.dropProcedureIfExists(procedureName, stmt); - TestUtils.dropTableIfExists(destTable, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(destTable), stmt); dropTVPS(); } @@ -511,7 +523,5 @@ public static void afterAll() throws SQLException { if (null != conn) { conn.close(); } - } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/dns/DNSRealmsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/dns/DNSRealmsTest.java deleted file mode 100644 index 02d7953819..0000000000 --- a/src/test/java/com/microsoft/sqlserver/jdbc/dns/DNSRealmsTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made - * available under the terms of the MIT License. See the LICENSE file in the project root for more information. - */ -package com.microsoft.sqlserver.jdbc.dns; - -import javax.naming.NamingException; - - -public class DNSRealmsTest { - - public static void main(String... args) { - if (args.length < 1) { - System.err.println("USAGE: list of domains to test for kerberos realms"); - } - for (String realmName : args) { - try { - System.out.print(DNSKerberosLocator.isRealmValid(realmName) ? "[ VALID ] " : "[INVALID] "); - } catch (NamingException err) { - System.err.print("[ FAILED] : " + err.getClass().getName() + ":" + err.getMessage()); - } - System.out.println(realmName); - } - } - -} 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 b5e2df0330..d7814f66ac 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/exception/ExceptionTest.java @@ -8,20 +8,23 @@ import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; +import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; -import java.sql.Connection; import java.sql.Statement; import java.text.MessageFormat; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerBulkCSVFileRecord; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -53,7 +56,7 @@ public void testBulkCSVFileRecordExceptionCause() throws Exception { } } - String waitForDelaySPName = "waitForDelaySP"; + static String waitForDelaySPName = RandomUtil.getIdentifier("waitForDelaySP"); final int waitForDelaySeconds = 10; /** @@ -66,13 +69,14 @@ public void testBulkCSVFileRecordExceptionCause() throws Exception { public void testSocketTimeoutExceptionCause() throws Exception { try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - TestUtils.dropProcedureIfExists(waitForDelaySPName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); createWaitForDelayPreocedure(conn); } + try (Connection conn = DriverManager .getConnection(connectionString + ";socketTimeout=" + (waitForDelaySeconds * 1000 / 2) + ";"); Statement stmt = conn.createStatement()) { - stmt.execute("exec " + waitForDelaySPName); + stmt.execute("exec " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName)); throw new Exception(TestResource.getResource("R_expectedExceptionNotThrown")); } catch (Exception e) { if (!(e instanceof SQLException)) { @@ -87,8 +91,16 @@ public void testSocketTimeoutExceptionCause() throws Exception { } private void createWaitForDelayPreocedure(SQLServerConnection conn) throws SQLException { - String sql = "CREATE PROCEDURE " + waitForDelaySPName + " AS" + " BEGIN" + " WAITFOR DELAY '00:00:" - + waitForDelaySeconds + "';" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName) + " AS" + " BEGIN" + + " WAITFOR DELAY '00:00:" + waitForDelaySeconds + "';" + " END"; conn.createStatement().execute(sql); } + + @AfterAll + public static void cleanup() throws SQLException { + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(waitForDelaySPName), stmt); + } + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java index d6b4d00e33..c4f3151ccc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataTest.java @@ -20,12 +20,13 @@ import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class ParameterMetaDataTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("Statement'Param") + "]"; + private static final String tableName = RandomUtil.getIdentifier("StatementParam"); /** * Test ParameterMetaData#isWrapperFor and ParameterMetaData#unwrap. @@ -36,9 +37,10 @@ public class ParameterMetaDataTest extends AbstractTest { public void testParameterMetaDataWrapper() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " (col1 int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int identity(1,1) primary key)"); try { - String query = "SELECT * from " + tableName + " where col1 = ?"; + String query = "SELECT * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col1 = ?"; try (PreparedStatement pstmt = con.prepareStatement(query)) { ParameterMetaData parameterMetaData = pstmt.getParameterMetaData(); @@ -46,7 +48,7 @@ public void testParameterMetaDataWrapper() throws SQLException { assertSame(parameterMetaData, parameterMetaData.unwrap(ParameterMetaData.class)); } } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -77,15 +79,17 @@ public void testSQLServerExceptionNotWrapped() throws SQLException { public void testNameWithBraces() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " ([c1_varchar(max)] varchar(max))"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)] varchar(max))"); try { - String query = "insert into " + tableName + " ([c1_varchar(max)]) values (?)"; + String query = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)]) values (?)"; try (PreparedStatement pstmt = con.prepareStatement(query)) { pstmt.getParameterMetaData(); } } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -99,9 +103,11 @@ public void testNameWithBraces() throws SQLException { public void testParameterMetaData() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " ([c1_varchar(max)] varchar(max), c2 decimal(38,5))"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)] varchar(max), c2 decimal(38,5))"); try { - String query = "insert into " + tableName + " ([c1_varchar(max)], c2) values (?,?)"; + String query = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1_varchar(max)], c2) values (?,?)"; try (PreparedStatement pstmt = con.prepareStatement(query)) { ParameterMetaData metadata = pstmt.getParameterMetaData(); @@ -112,7 +118,7 @@ public void testParameterMetaData() throws SQLException { assert (metadata.getScale(2) == 5); } } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java index 2cb73ee5b5..387451b789 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/parametermetadata/ParameterMetaDataWhiteSpaceTest.java @@ -22,37 +22,32 @@ import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class ParameterMetaDataWhiteSpaceTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("ParameterMetaDataWhiteSpaceTest") + "]"; - - private static Statement stmt = null; + private static final String tableName = RandomUtil.getIdentifier("ParameterMetaDataWhiteSpaceTest"); @BeforeAll public static void BeforeTests() throws SQLException { - connection = (SQLServerConnection) DriverManager.getConnection(connectionString); - stmt = connection.createStatement(); createCharTable(); } @AfterAll public static void dropTables() throws SQLException { - TestUtils.dropTableIfExists(tableName, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != connection) { - connection.close(); + try (SQLServerConnection connection = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } private static void createCharTable() throws SQLException { - stmt.execute("Create table " + tableName + " (c1 int)"); + try (SQLServerConnection connection = (SQLServerConnection) DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1 int)"); + } } /** @@ -62,8 +57,10 @@ private static void createCharTable() throws SQLException { */ @Test public void NormalTest() throws SQLException { - testUpdateWithTwoParameters("update " + tableName + " set c1 = ? where c1 = ?"); - testInsertWithOneParameter("insert into " + tableName + " (c1) values (?)"); + testUpdateWithTwoParameters( + "update " + AbstractSQLGenerator.escapeIdentifier(tableName) + " set c1 = ? where c1 = ?"); + testInsertWithOneParameter( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1) values (?)"); } /** @@ -97,13 +94,20 @@ public void FormFeedTest() throws SQLException { } private void testQueriesWithWhiteSpaces(String whiteSpace) throws SQLException { - testUpdateWithTwoParameters("update" + whiteSpace + tableName + " set c1 = ? where c1 = ?"); - testUpdateWithTwoParameters("update " + tableName + " set" + whiteSpace + "c1 = ? where c1 = ?"); - testUpdateWithTwoParameters("update " + tableName + " set c1 = ? where" + whiteSpace + "c1 = ?"); - - testInsertWithOneParameter("insert into " + tableName + "(c1) values (?)"); // no space between table name and - // column name - testInsertWithOneParameter("insert into" + whiteSpace + tableName + " (c1) values (?)"); + testUpdateWithTwoParameters( + "update" + whiteSpace + AbstractSQLGenerator.escapeIdentifier(tableName) + " set c1 = ? where c1 = ?"); + testUpdateWithTwoParameters("update " + AbstractSQLGenerator.escapeIdentifier(tableName) + " set" + whiteSpace + + "c1 = ? where c1 = ?"); + testUpdateWithTwoParameters("update " + AbstractSQLGenerator.escapeIdentifier(tableName) + " set c1 = ? where" + + whiteSpace + "c1 = ?"); + + testInsertWithOneParameter( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(c1) values (?)"); // no space + // between table + // name and + // column name + testInsertWithOneParameter( + "insert into" + whiteSpace + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1) values (?)"); } private void testUpdateWithTwoParameters(String sql) throws SQLException { @@ -127,14 +131,16 @@ private void testInsertWithOneParameter(String sql) throws SQLException { } private void insertTestRow(int id) throws SQLException { - try (PreparedStatement ps = connection.prepareStatement("insert into " + tableName + " (c1) values (?)")) { + try (PreparedStatement ps = connection.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1) values (?)")) { ps.setInt(1, id); ps.executeUpdate(); } } private boolean isIdPresentInTable(int id) throws SQLException { - try (PreparedStatement ps = connection.prepareStatement("select c1 from " + tableName + " where c1 = ?")) { + try (PreparedStatement ps = connection.prepareStatement( + "select c1 from " + AbstractSQLGenerator.escapeIdentifier(tableName) + " where c1 = ?")) { ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { return rs.next(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java index 2cad394a1a..80f13604c6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithBulkCopyTest.java @@ -26,31 +26,34 @@ import com.microsoft.sqlserver.jdbc.Geography; import com.microsoft.sqlserver.jdbc.Geometry; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class BatchExecutionWithBulkCopyTest extends AbstractTest { - static long UUID = System.currentTimeMillis();; - static String tableName = "BulkCopyParseTest" + UUID; - static String tableNameBulk = "BulkCopyParseTest" + UUID; - static String unsupportedTableName = "[BulkCopyUnsupportedTable'" + UUID + "]"; - static String squareBracketTableName = "[BulkCopy]]]]test'" + UUID + "]"; - static String doubleQuoteTableName = "\"BulkCopy\"\"\"\"test'" + UUID + "\""; + static String tableName = RandomUtil.getIdentifier("BulkCopyParseTest"); + static String tableNameBulk = RandomUtil.getIdentifier("BulkCopyParseTest"); + static String unsupportedTableName = RandomUtil.getIdentifier("BulkCopyUnsupportedTable'"); + static String squareBracketTableName = RandomUtil.getIdentifier("BulkCopy]]]]test'"); + static String doubleQuoteTableName = RandomUtil.getIdentifier("\"BulkCopy\"\"\"\"test\""); + static String schemaTableName = "\"dbo\" . /*some comment */ " + squareBracketTableName; @Test public void testIsInsert() throws Exception { try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - String valid1 = "INSERT INTO " + tableNameBulk + " values (1, 2)"; - String valid2 = " INSERT INTO " + tableNameBulk + " values (1, 2)"; - String valid3 = "/* asdf */ INSERT INTO " + tableNameBulk + " values (1, 2)"; - String invalid = "Select * from " + tableNameBulk; + String valid1 = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " values (1, 2)"; + String valid2 = " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " values (1, 2)"; + String valid3 = "/* asdf */ INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + + " values (1, 2)"; + String invalid = "Select * from " + AbstractSQLGenerator.escapeIdentifier(tableNameBulk); Method method = stmt.getClass().getDeclaredMethod("isInsert", String.class); method.setAccessible(true); @@ -65,7 +68,8 @@ public void testIsInsert() throws Exception { public void testComments() throws Exception { try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); PreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement("");) { - String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ tableNameBulk /*rando comment */" + String valid = "/* rando comment *//* rando comment */ INSERT /* rando comment */ INTO /* rando comment *//*rando comment*/ " + + AbstractSQLGenerator.escapeIdentifier(tableNameBulk) + " /*rando comment */" + " /* rando comment */values/* rando comment */ (1, 2)"; Field f1 = pstmt.getClass().getDeclaredField("localUserSQL"); @@ -76,7 +80,8 @@ public void testComments() throws Exception { boolean.class, boolean.class, boolean.class); method.setAccessible(true); - assertEquals("tableNameBulk", (String) method.invoke(pstmt, false, false, false, false)); + assertEquals(AbstractSQLGenerator.escapeIdentifier(tableNameBulk), + (String) method.invoke(pstmt, false, false, false, false)); } } @@ -155,8 +160,8 @@ public void testAll() throws Exception { @Test public void testAllcolumns() throws Exception { - String valid = "INSERT INTO " + tableName + " values " + "(" + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " - + "?, " + "?, " + "? " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values " + "(" + "?, " + + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "? " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -182,7 +187,8 @@ public void testAllcolumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -206,8 +212,8 @@ public void testAllcolumns() throws Exception { @Test public void testMixColumns() throws Exception { - String valid = "INSERT INTO " + tableName + " (c1, c3, c5, c8) values " + "(" + "?, " + "?, " + "?, " + "? " - + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1, c3, c5, c8) values " + + "(" + "?, " + "?, " + "?, " + "? " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -228,7 +234,8 @@ public void testMixColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -254,8 +261,9 @@ public void testMixColumns() throws Exception { @Test public void testNullOrEmptyColumns() throws Exception { - String valid = "INSERT INTO " + tableName + " (c1, c2, c3, c4, c5, c6, c7) values " + "(" + "?, " + "?, " - + "?, " + "?, " + "?, " + "?, " + "? " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (c1, c2, c3, c4, c5, c6, c7) values " + "(" + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "? " + + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -275,7 +283,8 @@ public void testNullOrEmptyColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -300,8 +309,8 @@ public void testNullOrEmptyColumns() throws Exception { // Non-parameterized queries are not supported anymore. // @Test public void testAllFilledColumns() throws Exception { - String valid = "INSERT INTO " + tableName + " values " + "(" + "1234, " + "false, " + "a, " + "null, " - + "null, " + "123.45, " + "b, " + "varc, " + "sadf, " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values " + "(" + "1234, " + + "false, " + "a, " + "null, " + "null, " + "123.45, " + "b, " + "varc, " + "sadf, " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -314,7 +323,8 @@ public void testAllFilledColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -338,7 +348,7 @@ public void testAllFilledColumns() throws Exception { @Test public void testSquareBracketAgainstDB() throws Exception { - String valid = "insert into " + squareBracketTableName + " values (?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + " values (?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -347,8 +357,9 @@ public void testSquareBracketAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(squareBracketTableName, stmt); - String createTable = "create table " + squareBracketTableName + " (c1 int)"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + + " (c1 int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -356,7 +367,8 @@ public void testSquareBracketAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -366,7 +378,7 @@ public void testSquareBracketAgainstDB() throws Exception { @Test public void testDoubleQuoteAgainstDB() throws Exception { - String valid = "insert into " + doubleQuoteTableName + " values (?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName) + " values (?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -375,8 +387,9 @@ public void testDoubleQuoteAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(doubleQuoteTableName, stmt); - String createTable = "create table " + doubleQuoteTableName + " (c1 int)"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName) + + " (c1 int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -384,7 +397,8 @@ public void testDoubleQuoteAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + doubleQuoteTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -394,8 +408,7 @@ public void testDoubleQuoteAgainstDB() throws Exception { @Test public void testSchemaAgainstDB() throws Exception { - String schemaTableName = "\"dbo\" . /*some comment */ " + squareBracketTableName; - String valid = "insert into " + schemaTableName + " values (?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(schemaTableName) + " values (?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -404,9 +417,8 @@ public void testSchemaAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists("[dbo]." + squareBracketTableName, stmt); - - String createTable = "create table " + schemaTableName + " (c1 int)"; + TestUtils.dropTableIfExists("[dbo]." + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(schemaTableName) + " (c1 int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -414,7 +426,8 @@ public void testSchemaAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + schemaTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(schemaTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -424,7 +437,8 @@ public void testSchemaAgainstDB() throws Exception { @Test public void testColumnNameMixAgainstDB() throws Exception { - String valid = "insert into " + squareBracketTableName + " ([c]]]]1], [c]]]]2]) values (?, 1)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + + " ([c]]]]1], [c]]]]2]) values (?, 1)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -433,8 +447,9 @@ public void testColumnNameMixAgainstDB() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(squareBracketTableName, stmt); - String createTable = "create table " + squareBracketTableName + " ([c]]]]1] int, [c]]]]2] int)"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName) + + " ([c]]]]1] int, [c]]]]2] int)"; stmt.execute(createTable); pstmt.setInt(1, 1); @@ -442,7 +457,8 @@ public void testColumnNameMixAgainstDB() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + squareBracketTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(squareBracketTableName))) { rs.next(); assertEquals(1, rs.getObject(1)); @@ -452,8 +468,8 @@ public void testColumnNameMixAgainstDB() throws Exception { @Test public void testAllColumnsLargeBatch() throws Exception { - String valid = "INSERT INTO " + tableName + " values " + "(" + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " - + "?, " + "?, " + "? " + ")"; + String valid = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values " + "(" + "?, " + + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "?, " + "? " + ")"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -479,7 +495,8 @@ public void testAllColumnsLargeBatch() throws Exception { pstmt.executeLargeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { Object[] expected = new Object[9]; @@ -503,7 +520,7 @@ public void testAllColumnsLargeBatch() throws Exception { @Test public void testIllegalNumberOfArgNoColumnList() throws Exception { - String invalid = "insert into " + tableName + " values (?, ?,? ,?) "; + String invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values (?, ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -524,7 +541,8 @@ public void testIllegalNumberOfArgNoColumnList() throws Exception { assertEquals("Column name or number of supplied values does not match table definition.", e.getMessage()); } - invalid = "insert into " + tableName + " (c1, c2, c3) values (?, ?,? ,?) "; + invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (c1, c2, c3) values (?, ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -550,7 +568,8 @@ public void testIllegalNumberOfArgNoColumnList() throws Exception { @Test public void testNonParameterizedQuery() throws Exception { - String invalid = "insert into " + tableName + " values ((SELECT * from table where c1=?), ?,? ,?) "; + String invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " values ((SELECT * from table where c1=?), ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -571,7 +590,7 @@ public void testNonParameterizedQuery() throws Exception { assertEquals("Incorrect syntax near the keyword 'table'.", e.getMessage()); } - invalid = "insert into " + tableName + " values ('?', ?,? ,?) "; + invalid = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values ('?', ?,? ,?) "; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(invalid); @@ -594,7 +613,8 @@ public void testNonParameterizedQuery() throws Exception { @Test public void testNonSupportedColumns() throws Exception { - String valid = "insert into " + unsupportedTableName + " values (?, ?, ?, ?)"; + String valid = "insert into " + AbstractSQLGenerator.escapeIdentifier(unsupportedTableName) + + " values (?, ?, ?, ?)"; try (Connection connection = DriverManager.getConnection(connectionString + ";useBulkCopyForBatchInsert=true;"); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(valid); @@ -603,9 +623,9 @@ public void testNonSupportedColumns() throws Exception { f1.setAccessible(true); f1.set(connection, true); - TestUtils.dropTableIfExists(unsupportedTableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(unsupportedTableName), stmt); - String createTable = "create table " + unsupportedTableName + String createTable = "create table " + AbstractSQLGenerator.escapeIdentifier(unsupportedTableName) + " (c1 geometry, c2 geography, c3 datetime, c4 smalldatetime)"; stmt.execute(createTable); @@ -621,7 +641,8 @@ public void testNonSupportedColumns() throws Exception { pstmt.executeBatch(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + unsupportedTableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(unsupportedTableName))) { rs.next(); assertEquals(g1.toString(), Geometry.STGeomFromWKB((byte[]) rs.getObject(1)).toString()); assertEquals(g2.toString(), Geography.STGeomFromWKB((byte[]) rs.getObject(2)).toString()); @@ -636,10 +657,10 @@ public void testSetup() throws TestAbortedException, Exception { try (Connection connection = DriverManager .getConnection(connectionString + ";useBulkCopyForBatchInsert=true;")) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); - String sql1 = "create table " + tableName + " " + "(" + "c1 int DEFAULT 1234, " + "c2 bit, " - + "c3 char DEFAULT NULL, " + "c4 date, " + "c5 datetime2, " + "c6 float, " + "c7 nchar, " - + "c8 varchar(20), " + "c9 varchar(max)" + ")"; + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " " + "(" + + "c1 int DEFAULT 1234, " + "c2 bit, " + "c3 char DEFAULT NULL, " + "c4 date, " + + "c5 datetime2, " + "c6 float, " + "c7 nchar, " + "c8 varchar(20), " + "c9 varchar(max)" + ")"; stmt.execute(sql1); } @@ -650,10 +671,12 @@ public void testSetup() throws TestAbortedException, Exception { public static void terminateVariation() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString)) { try (Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(squareBracketTableName, stmt); - TestUtils.dropTableIfExists(doubleQuoteTableName, stmt); - TestUtils.dropTableIfExists(unsupportedTableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableNameBulk), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(unsupportedTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(squareBracketTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(doubleQuoteTableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(schemaTableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java index a41cf3c47a..8694c91b6d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/BatchExecutionWithNullTest.java @@ -12,7 +12,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.sql.Types; import org.junit.jupiter.api.AfterAll; @@ -22,9 +21,11 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; @@ -32,12 +33,7 @@ @RunWith(JUnitPlatform.class) public class BatchExecutionWithNullTest extends AbstractTest { - static Connection conn = null; - static Statement stmt = null; - static Connection connection = null; - static PreparedStatement pstmt = null; - static PreparedStatement pstmt1 = null; - static ResultSet rs = null; + static String tableName = RandomUtil.getIdentifier("esimple"); /** * Test with combination of setString and setNull which cause the "Violation of PRIMARY KEY constraint and @@ -48,49 +44,49 @@ public class BatchExecutionWithNullTest extends AbstractTest { @Test public void testAddBatch2() throws SQLException { // try { - String sPrepStmt = "insert into esimple (id, name) values (?, ?)"; + String sPrepStmt = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id, name) values (?, ?)"; int updateCountlen = 0; int key = 42; // this is the minimum sequence, I've found to trigger the error\ - conn = DriverManager.getConnection(connectionString); - pstmt = conn.prepareStatement(sPrepStmt); - pstmt.setInt(1, key++); - pstmt.setNull(2, Types.VARCHAR); - pstmt.addBatch(); - - pstmt.setInt(1, key++); - pstmt.setString(2, "FOO"); - pstmt.addBatch(); - - pstmt.setInt(1, key++); - pstmt.setNull(2, Types.VARCHAR); - pstmt.addBatch(); + try (Connection conn = DriverManager.getConnection(connectionString); + PreparedStatement pstmt = conn.prepareStatement(sPrepStmt)) { + pstmt.setInt(1, key++); + pstmt.setNull(2, Types.VARCHAR); + pstmt.addBatch(); - int[] updateCount = pstmt.executeBatch(); - updateCountlen += updateCount.length; + pstmt.setInt(1, key++); + pstmt.setString(2, "FOO"); + pstmt.addBatch(); - pstmt.setInt(1, key++); - pstmt.setString(2, "BAR"); - pstmt.addBatch(); + pstmt.setInt(1, key++); + pstmt.setNull(2, Types.VARCHAR); + pstmt.addBatch(); - pstmt.setInt(1, key++); - pstmt.setNull(2, Types.VARCHAR); - pstmt.addBatch(); + int[] updateCount = pstmt.executeBatch(); + updateCountlen += updateCount.length; - updateCount = pstmt.executeBatch(); - updateCountlen += updateCount.length; + pstmt.setInt(1, key++); + pstmt.setString(2, "BAR"); + pstmt.addBatch(); - assertTrue(updateCountlen == 5, TestResource.getResource("R_addBatchFailed")); + pstmt.setInt(1, key++); + pstmt.setNull(2, Types.VARCHAR); + pstmt.addBatch(); - String sPrepStmt1 = "select count(*) from esimple"; + updateCount = pstmt.executeBatch(); + updateCountlen += updateCount.length; - pstmt1 = connection.prepareStatement(sPrepStmt1); - rs = pstmt1.executeQuery(); - rs.next(); - assertTrue(rs.getInt(1) == 5, TestResource.getResource("R_insertBatchFailed")); - pstmt1.close(); + assertTrue(updateCountlen == 5, TestResource.getResource("R_addBatchFailed")); + } + String sPrepStmt1 = "select count(*) from " + AbstractSQLGenerator.escapeIdentifier(tableName); + try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1); ResultSet rs = pstmt1.executeQuery()) { + rs.next(); + assertTrue(rs.getInt(1) == 5, TestResource.getResource("R_insertBatchFailed")); + pstmt1.close(); + } } /** @@ -100,8 +96,10 @@ public void testAddBatch2() throws SQLException { */ @Test public void testAddbatch2AEOnConnection() throws SQLException { - connection = DriverManager.getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); - testAddBatch2(); + try (Connection connection = DriverManager + .getConnection(connectionString + ";columnEncryptionSetting=Enabled;")) { + testAddBatch2(); + } } @BeforeEach @@ -110,35 +108,21 @@ public void testSetup() throws TestAbortedException, Exception { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } - connection = DriverManager.getConnection(connectionString); - SQLServerStatement stmt = (SQLServerStatement) connection.createStatement(); - TestUtils.dropTableIfExists("esimple", stmt); - String sql1 = "create table esimple (id integer not null, name varchar(255), constraint pk_esimple primary key (id))"; - stmt.execute(sql1); - stmt.close(); + try (Connection connection = DriverManager.getConnection(connectionString); + SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id integer not null, name varchar(255), constraint pk_esimple primary key (id))"; + stmt.execute(sql1); + stmt.close(); + } } @AfterAll public static void terminateVariation() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) conn.createStatement()) { - TestUtils.dropTableIfExists("esimple", stmt); - } - - if (null != pstmt) { - pstmt.close(); - } - if (null != pstmt1) { - pstmt1.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } - if (null != conn) { - conn.close(); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java index 3ba34122b3..749e7a799e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/preparedStatement/RegressionTest.java @@ -22,9 +22,11 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -35,7 +37,10 @@ */ @RunWith(JUnitPlatform.class) public class RegressionTest extends AbstractTest { - static Connection con = null; + + static String tableName = RandomUtil.getIdentifier("PrepareDStatementTestTable"); + static String tableName2 = RandomUtil.getIdentifier("PrepareDStatementTestTable2"); + static String schemaName = RandomUtil.getIdentifier("schemaName"); /** * Setup before test @@ -44,9 +49,8 @@ public class RegressionTest extends AbstractTest { */ @BeforeAll public static void setupTest() throws SQLException { - con = DriverManager.getConnection(connectionString); - try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("x", stmt); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } @@ -57,8 +61,11 @@ public static void setupTest() throws SQLException { */ @Test public void createViewTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create view x as select 1 a"); - PreparedStatement pstmt2 = con.prepareStatement("drop view x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create view " + AbstractSQLGenerator.escapeIdentifier(tableName) + " as select 1 a"); + PreparedStatement pstmt2 = con + .prepareStatement("drop view " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { @@ -74,8 +81,11 @@ public void createViewTest() throws SQLException { */ @Test public void createSchemaTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create schema x"); - PreparedStatement pstmt2 = con.prepareStatement("drop schema x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con + .prepareStatement("create schema " + AbstractSQLGenerator.escapeIdentifier(schemaName)); + PreparedStatement pstmt2 = con + .prepareStatement("drop schema " + AbstractSQLGenerator.escapeIdentifier(schemaName))) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { @@ -91,8 +101,11 @@ public void createSchemaTest() throws SQLException { */ @Test public void createTableTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create table x (col1 int)"); - PreparedStatement pstmt2 = con.prepareStatement("drop table x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); + PreparedStatement pstmt2 = con + .prepareStatement("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); } catch (SQLException e) { @@ -108,9 +121,13 @@ public void createTableTest() throws SQLException { */ @Test public void alterTableTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create table x (col1 int)"); - PreparedStatement pstmt2 = con.prepareStatement("ALTER TABLE x ADD column_name char;"); - PreparedStatement pstmt3 = con.prepareStatement("drop table x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); + PreparedStatement pstmt2 = con.prepareStatement( + "ALTER TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " ADD column_name char;"); + PreparedStatement pstmt3 = con + .prepareStatement("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); pstmt3.execute(); @@ -127,10 +144,15 @@ public void alterTableTest() throws SQLException { */ @Test public void grantTest() throws SQLException { - try (PreparedStatement pstmt1 = con.prepareStatement("create table x (col1 int)"); - PreparedStatement pstmt2 = con.prepareStatement("grant select on x to public"); - PreparedStatement pstmt3 = con.prepareStatement("revoke select on x from public"); - PreparedStatement pstmt4 = con.prepareStatement("drop table x")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement pstmt1 = con.prepareStatement( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int)"); + PreparedStatement pstmt2 = con.prepareStatement( + "grant select on " + AbstractSQLGenerator.escapeIdentifier(tableName) + " to public"); + PreparedStatement pstmt3 = con.prepareStatement( + "revoke select on " + AbstractSQLGenerator.escapeIdentifier(tableName) + " from public"); + PreparedStatement pstmt4 = con + .prepareStatement("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName))) { pstmt1.execute(); pstmt2.execute(); pstmt3.execute(); @@ -163,18 +185,21 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); con.setAutoCommit(false); // create a table with two columns boolean createPrimaryKey = false; try { - stmt.execute("if object_id('TEST_TABLE', 'U') is not null\ndrop table TEST_TABLE;"); + stmt.execute("if object_id('" + TestUtils.escapeSingleQuotes(tableName2) + + "', 'U') is not null\ndrop table " + AbstractSQLGenerator.escapeIdentifier(tableName2)); if (createPrimaryKey) { - stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max), primary key (ID) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max), primary key (ID) );"); } else { - stmt.execute("create table TEST_TABLE ( ID int, DATA nvarchar(max) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max) );"); } } catch (Exception e) { fail(e.toString()); @@ -191,7 +216,8 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { String[] values = {"a", "b", largeString, "d", "e"}; // insert five rows into the table; use a batch for each row - try (PreparedStatement pstmt = con.prepareStatement("insert into TEST_TABLE values (?,?)")) { + try (PreparedStatement pstmt = con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName2) + " values (?,?)")) { // 0,a pstmt.setInt(1, 0); pstmt.setNString(2, values[0]); @@ -226,7 +252,8 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { // check the data in the table Map selectedValues = new LinkedHashMap<>(); int id = 0; - try (PreparedStatement pstmt = con.prepareStatement("select * from TEST_TABLE;")) { + try (PreparedStatement pstmt = con + .prepareStatement("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName2) + ";")) { try (ResultSet rs = pstmt.executeQuery()) { int i = 0; while (rs.next()) { @@ -240,7 +267,7 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { } } } finally { - TestUtils.dropTableIfExists("TEST_TABLE", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); } } } @@ -253,19 +280,22 @@ private void batchWithLargeStringTestInternal(String mode) throws Exception { */ @Test public void addBatchWithLargeStringTest() throws SQLException { - try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("TEST_TABLE", stmt); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); con.setAutoCommit(false); // create a table with two columns boolean createPrimaryKey = false; try { - stmt.execute("if object_id('testTable', 'U') is not null\ndrop table testTable;"); + stmt.execute("if object_id('" + TestUtils.escapeSingleQuotes(tableName2) + + "', 'U') is not null\ndrop table " + AbstractSQLGenerator.escapeIdentifier(tableName2)); if (createPrimaryKey) { - stmt.execute("create table testTable ( ID int, DATA nvarchar(max), primary key (ID) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max), primary key (ID) );"); } else { - stmt.execute("create table testTable ( ID int, DATA nvarchar(max) );"); + stmt.execute("create table " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " ( ID int, DATA nvarchar(max) );"); } } catch (Exception e) { fail(e.toString()); @@ -280,7 +310,8 @@ public void addBatchWithLargeStringTest() throws SQLException { String largeString = stringBuilder.toString(); // insert five rows into the table; use a batch for each row - try (PreparedStatement pstmt = con.prepareStatement("insert into testTable values (?,?), (?,?);")) { + try (PreparedStatement pstmt = con.prepareStatement( + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName2) + " values (?,?), (?,?);")) { // 0,a // 1,b pstmt.setInt(1, 0); @@ -329,7 +360,7 @@ public void addBatchWithLargeStringTest() throws SQLException { catch (Exception e) { fail(e.toString()); } finally { - TestUtils.dropTableIfExists("testTable", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); } } } @@ -341,12 +372,9 @@ public void addBatchWithLargeStringTest() throws SQLException { */ @AfterAll public static void cleanup() throws SQLException { - try (Statement stmt = con.createStatement()) { - TestUtils.dropTableIfExists("x", stmt); - TestUtils.dropTableIfExists("TEST_TABLE", stmt); - } - if (null != con) { - con.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName2), stmt); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java index eb9bd0c3e6..098f789d5c 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/DataClassificationTest.java @@ -18,12 +18,13 @@ import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.jdbc.TestUtils; import com.microsoft.sqlserver.jdbc.dataclassification.SensitivityProperty; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class DataClassificationTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("DataClassification") + "]"; + private static final String tableName = RandomUtil.getIdentifier("DataClassification"); /** * Tests data classification metadata information from SQL Server @@ -38,7 +39,7 @@ public void testDataClassificationMetadata() throws Exception { if (TestUtils.serverSupportsDataClassification(stmt)) { createTable(connection, stmt); runTestsForServer(stmt); - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -51,26 +52,26 @@ public void testDataClassificationMetadata() throws Exception { * @throws SQLException */ private void createTable(Connection connection, Statement stmt) throws SQLException { - String createQuery = "CREATE TABLE " + tableName + " (" + "[Id] [int] IDENTITY(1,1) NOT NULL," - + "[CompanyName] [nvarchar](40) NOT NULL," + "[ContactName] [nvarchar](50) NULL," - + "[ContactTitle] [nvarchar](40) NULL," + "[City] [nvarchar](40) NULL," - + "[CountryName] [nvarchar](40) NULL," + String createQuery = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (" + + "[Id] [int] IDENTITY(1,1) NOT NULL," + "[CompanyName] [nvarchar](40) NOT NULL," + + "[ContactName] [nvarchar](50) NULL," + "[ContactTitle] [nvarchar](40) NULL," + + "[City] [nvarchar](40) NULL," + "[CountryName] [nvarchar](40) NULL," + "[Phone] [nvarchar](30) MASKED WITH (FUNCTION = 'default()') NULL," + "[Fax] [nvarchar](30) MASKED WITH (FUNCTION = 'default()') NULL)"; stmt.execute(createQuery); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".CompanyName WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Company name', INFORMATION_TYPE_ID='COMPANY')"); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".ContactName WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Person name', INFORMATION_TYPE_ID='NAME')"); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".Phone WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Contact Information', INFORMATION_TYPE_ID='CONTACT')"); - stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + tableName + stmt.execute("ADD SENSITIVITY CLASSIFICATION TO " + AbstractSQLGenerator.escapeIdentifier(tableName) + ".Fax WITH (LABEL='PII', LABEL_ID='L1', INFORMATION_TYPE='Contact Information', INFORMATION_TYPE_ID='CONTACT')"); // INSERT ROWS OF DATA - try (PreparedStatement ps = connection - .prepareStatement("INSERT INTO " + tableName + " VALUES (?,?,?,?,?,?,?)")) { + try (PreparedStatement ps = connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (?,?,?,?,?,?,?)")) { ps.setString(1, "Exotic Liquids"); ps.setString(2, "Charlotte Cooper"); @@ -108,7 +109,8 @@ private void createTable(Connection connection, Statement stmt) throws SQLExcept * @throws Exception */ private void runTestsForServer(Statement stmt) throws Exception { - try (SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("SELECT * FROM " + tableName)) { + try (SQLServerResultSet rs = (SQLServerResultSet) stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { verifySensitivityClassification(rs); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java index 845f4a057b..574a928dfd 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/resultset/ResultSetTest.java @@ -34,12 +34,15 @@ import com.microsoft.sqlserver.jdbc.ISQLServerResultSet; import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class ResultSetTest extends AbstractTest { - private static final String tableName = "[" + RandomUtil.getIdentifier("StatementParam") + "]"; + private static final String tableName = RandomUtil.getIdentifier("StatementParam"); + + static final String uuid = UUID.randomUUID().toString(); /** * Tests proper exception for unsupported operation @@ -49,37 +52,39 @@ public class ResultSetTest extends AbstractTest { @Test public void testJdbc41ResultSetMethods() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " ( " + "col1 int, " + "col2 varchar(512), " - + "col3 float, " + "col4 decimal(10,5), " + "col5 uniqueidentifier, " + "col6 xml, " - + "col7 varbinary(max), " + "col8 text, " + "col9 ntext, " + "col10 varbinary(max), " + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " ( " + "col1 int, " + + "col2 varchar(512), " + "col3 float, " + "col4 decimal(10,5), " + "col5 uniqueidentifier, " + + "col6 xml, " + "col7 varbinary(max), " + "col8 text, " + "col9 ntext, " + "col10 varbinary(max), " + "col11 date, " + "col12 time, " + "col13 datetime2, " + "col14 datetimeoffset, " + "col15 decimal(10,9), " + "col16 decimal(38,38), " + "order_column int identity(1,1) primary key)"); try { - stmt.executeUpdate("Insert into " + tableName + " values(" + "1, " // col1 - + "'hello', " // col2 - + "2.0, " // col3 - + "123.45, " // col4 - + "'6F9619FF-8B86-D011-B42D-00C04FC964FF', " // col5 - + "'', " // col6 - + "0x63C34D6BCAD555EB64BF7E848D02C376, " // col7 - + "'text', " // col8 - + "'ntext', " // col9 - + "0x63C34D6BCAD555EB64BF7E848D02C376," // col10 - + "'2017-05-19'," // col11 - + "'10:47:15.1234567'," // col12 - + "'2017-05-19T10:47:15.1234567'," // col13 - + "'2017-05-19T10:47:15.1234567+02:00'," // col14 - + "0.123456789, " // col15 - + "0.1234567890123456789012345678901234567" // col16 - + ")"); - - stmt.executeUpdate("Insert into " + tableName + " values(" + "null, " + "null, " + "null, " + "null, " + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(" + "1, " // col1 + + "'hello', " // col2 + + "2.0, " // col3 + + "123.45, " // col4 + + "'" + uuid + "', " // col5 + + "'', " // col6 + + "0x63C34D6BCAD555EB64BF7E848D02C376, " // col7 + + "'text', " // col8 + + "'ntext', " // col9 + + "0x63C34D6BCAD555EB64BF7E848D02C376," // col10 + + "'2017-05-19'," // col11 + + "'10:47:15.1234567'," // col12 + + "'2017-05-19T10:47:15.1234567'," // col13 + + "'2017-05-19T10:47:15.1234567+02:00'," // col14 + + "0.123456789, " // col15 + + "0.1234567890123456789012345678901234567" // col16 + + ")"); + + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(" + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " - + "null, " + "null, " + "null, " + "null)"); + + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null, " + "null)"); - try (ResultSet rs = stmt.executeQuery("select * from " + tableName + " order by order_column")) { + try (ResultSet rs = stmt.executeQuery("select * from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " order by order_column")) { // test non-null values assertTrue(rs.next()); assertEquals(Byte.valueOf((byte) 1), rs.getObject(1, Byte.class)); @@ -105,9 +110,8 @@ public void testJdbc41ResultSetMethods() throws SQLException { assertEquals(0, rs.getObject(4, BigDecimal.class).compareTo(new BigDecimal("123.45"))); assertEquals(0, rs.getObject("col4", BigDecimal.class).compareTo(new BigDecimal("123.45"))); - assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), rs.getObject(5, UUID.class)); - assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), - rs.getObject("col5", UUID.class)); + assertEquals(UUID.fromString(uuid), rs.getObject(5, UUID.class)); + assertEquals(UUID.fromString(uuid), rs.getObject("col5", UUID.class)); SQLXML sqlXml; sqlXml = rs.getObject(6, SQLXML.class); @@ -239,7 +243,7 @@ public void testJdbc41ResultSetMethods() throws SQLException { assertFalse(rs.next()); } } finally { - stmt.executeUpdate("drop table " + tableName); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } } @@ -260,10 +264,13 @@ public void testGetObjectAsLocalDateTime() throws SQLException { final String testValueTime = "02:00:00.1234567"; final String testValueDateTime = testValueDate + "T" + testValueTime; - stmt.executeUpdate("CREATE TABLE " + tableName + " (id INT PRIMARY KEY, dt2 DATETIME2)"); - stmt.executeUpdate("INSERT INTO " + tableName + " (id, dt2) VALUES (1, '" + testValueDateTime + "')"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id INT PRIMARY KEY, dt2 DATETIME2)"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (id, dt2) VALUES (1, '" + testValueDateTime + "')"); - try (ResultSet rs = stmt.executeQuery("SELECT dt2 FROM " + tableName + " WHERE id=1")) { + try (ResultSet rs = stmt.executeQuery( + "SELECT dt2 FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE id=1")) { rs.next(); LocalDateTime expectedLocalDateTime = LocalDateTime.parse(testValueDateTime); @@ -278,7 +285,7 @@ public void testGetObjectAsLocalDateTime() throws SQLException { LocalTime actualLocalTime = rs.getObject(1, LocalTime.class); assertEquals(expectedLocalTime, actualLocalTime); } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); TimeZone.setDefault(prevTimeZone); } } @@ -293,17 +300,18 @@ public void testGetObjectAsLocalDateTime() throws SQLException { public void testResultSetWrapper() throws SQLException { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate( - "create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); - try (ResultSet rs = stmt.executeQuery("select * from " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { assertTrue(rs.isWrapperFor(ResultSet.class)); assertTrue(rs.isWrapperFor(ISQLServerResultSet.class)); assertSame(rs, rs.unwrap(ResultSet.class)); assertSame(rs, rs.unwrap(ISQLServerResultSet.class)); } finally { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypesTest.java similarity index 82% rename from src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java rename to src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypesTest.java index 446ac55d7d..22408852f0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPAllTypesTest.java @@ -17,11 +17,13 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.ComparisonUtil; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; @@ -30,12 +32,12 @@ @RunWith(JUnitPlatform.class) -public class TVPAllTypes extends AbstractTest { +public class TVPAllTypesTest extends AbstractTest { private static Connection conn = null; static Statement stmt = null; - private static String tvpName = "TVPAllTypesTable_char_TVP"; - private static String procedureName = "TVPAllTypesTable_char_SP"; + private static String tvpName; + private static String procedureName; private static DBTable tableSrc = null; private static DBTable tableDest = null; @@ -94,7 +96,7 @@ private void testTVPStoredProcedureResultSet(boolean setSelectMethod, Integer re setupVariation(setSelectMethod, resultSetType, resultSetConcurrency); try (ResultSet rs = stmt.executeQuery("select * from " + tableSrc.getEscapedTableName()); SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) conn - .prepareCall("{call " + procedureName + "(?)}")) { + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}")) { Cstmt.setStructured(1, tvpName, rs); Cstmt.execute(); @@ -139,25 +141,25 @@ public void testTVPDataTable() throws SQLException { } private static void createPreocedure(String procedureName, String destTable) throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + destTable + " SELECT * FROM @InputData" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + + destTable + " SELECT * FROM @InputData" + " END"; stmt.execute(sql); } - private static void dropTVPS(String tvpName) throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); - } - - private static void createTVPS(String TVPName, String TVPDefinition) throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + TVPName + " as table (" + TVPDefinition + ");"; + private static void createTVPS(String tvpName, String TVPDefinition) throws SQLException { + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (" + + TVPDefinition + ");"; stmt.executeUpdate(TVPCreateCmd); } private void setupVariation(boolean setSelectMethod, Integer resultSetType, Integer resultSetConcurrency) throws SQLException { + tvpName = RandomUtil.getIdentifier("TVP"); + procedureName = RandomUtil.getIdentifier("TVP"); + if (setSelectMethod) { conn = DriverManager.getConnection(connectionString + ";selectMethod=cursor;"); } else { @@ -170,8 +172,8 @@ private void setupVariation(boolean setSelectMethod, Integer resultSetType, stmt = conn.createStatement(); } - TestUtils.dropProcedureIfExists(procedureName, stmt); - dropTVPS(tvpName); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tvpName), stmt); try (DBConnection dbConnection = new DBConnection(connectionString); DBStatement dbStmt = dbConnection.createStatement()) { @@ -190,10 +192,10 @@ private void setupVariation(boolean setSelectMethod, Integer resultSetType, } private void terminateVariation() throws SQLException { - TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); TestUtils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); TestUtils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); - dropTVPS(tvpName); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tvpName), stmt); if (null != stmt) { stmt.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java index 507d31c924..25c6261026 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPIssuesTest.java @@ -20,27 +20,27 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest;; @RunWith(JUnitPlatform.class) public class TVPIssuesTest extends AbstractTest { - static Connection connection = null; - static Statement stmt = null; - private static String tvp_varcharMax = "TVPIssuesTest_varcharMax_TVP"; - private static String spName_varcharMax = "TVPIssuesTest_varcharMax_SP"; - private static String srcTable_varcharMax = "TVPIssuesTest_varcharMax_srcTable"; - private static String desTable_varcharMax = "TVPIssuesTest_varcharMax_destTable"; + private static String tvp_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_TVP"); + private static String spName_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_SP"); + private static String srcTable_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_srcTable"); + private static String desTable_varcharMax = RandomUtil.getIdentifier("TVPIssuesTest_varcharMax_destTable"); - private static String tvp_time_6 = "TVPIssuesTest_time_6_TVP"; - private static String srcTable_time_6 = "TVPIssuesTest_time_6_srcTable"; - private static String desTable_time_6 = "TVPIssuesTest_time_6_destTable"; + private static String tvp_time_6 = RandomUtil.getIdentifier("TVPIssuesTest_time_6_TVP"); + private static String srcTable_time_6 = RandomUtil.getIdentifier("TVPIssuesTest_time_6_srcTable"); + private static String desTable_time_6 = RandomUtil.getIdentifier("TVPIssuesTest_time_6_destTable"); private static String expectedTime6value = "15:39:27.616667"; @@ -49,10 +49,12 @@ public void tryTVPRSvarcharMax4000Issue() throws Exception { setup(); try (SQLServerStatement st = (SQLServerStatement) connection.createStatement(); - ResultSet rs = st.executeQuery("select * from " + srcTable_varcharMax); + ResultSet rs = st + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax)); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + desTable_varcharMax + " select * from ? ;")) { + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax) + + " select * from ? ;")) { pstmt.setStructured(1, tvp_varcharMax, rs); pstmt.execute(); @@ -69,11 +71,11 @@ public void tryTVPRSvarcharMax4000Issue() throws Exception { @Test public void testExceptionWithInvalidStoredProcedureName() throws Exception { SQLServerStatement st = (SQLServerStatement) connection.createStatement(); - ResultSet rs = st.executeQuery("select * from " + srcTable_varcharMax); + ResultSet rs = st.executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax)); dropProcedure(); - final String sql = "{call " + spName_varcharMax + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(spName_varcharMax) + "(?)}"; try (SQLServerCallableStatement Cstmt = (SQLServerCallableStatement) connection.prepareCall(sql)) { Cstmt.setObject(1, rs); @@ -98,9 +100,13 @@ public void testExceptionWithInvalidStoredProcedureName() throws Exception { public void tryTVPPrecisionmissedissue315() throws Exception { setup(); - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable_time_6); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement(); + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6)); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + desTable_time_6 + " select * from ? ;")) { + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable_time_6) + + " select * from ? ;")) { pstmt.setStructured(1, tvp_time_6, rs); pstmt.execute(); @@ -109,7 +115,8 @@ public void tryTVPPrecisionmissedissue315() throws Exception { } private void testCharDestTable() throws SQLException, IOException { - try (ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_varcharMax)) { + try (ResultSet rs = connection.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax))) { while (rs.next()) { assertEquals(rs.getString(1).length(), 4001, TestResource.getResource("R_lengthTruncated")); } @@ -117,7 +124,8 @@ private void testCharDestTable() throws SQLException, IOException { } private void testTime6DestTable() throws SQLException, IOException { - try (ResultSet rs = connection.createStatement().executeQuery("select * from " + desTable_time_6)) { + try (ResultSet rs = connection.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable_time_6))) { while (rs.next()) { assertEquals(rs.getString(1), expectedTime6value, TestResource.getResource("R_timeValueTruncated")); } @@ -126,45 +134,52 @@ private void testTime6DestTable() throws SQLException, IOException { @BeforeAll public static void beforeAll() throws SQLException { - connection = DriverManager.getConnection(connectionString); - stmt = connection.createStatement(); - - dropProcedure(); - - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_varcharMax - + "') " + " drop type " + tvp_varcharMax); - TestUtils.dropTableIfExists(srcTable_varcharMax, stmt); - TestUtils.dropTableIfExists(desTable_varcharMax, stmt); - - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_time_6 - + "') " + " drop type " + tvp_time_6); - TestUtils.dropTableIfExists(srcTable_time_6, stmt); - TestUtils.dropTableIfExists(desTable_time_6, stmt); - - String sql = "create table " + srcTable_varcharMax + " (c1 varchar(max) null);"; - stmt.execute(sql); - sql = "create table " + desTable_varcharMax + " (c1 varchar(max) null);"; - stmt.execute(sql); - - sql = "create table " + srcTable_time_6 + " (c1 time(6) null);"; - stmt.execute(sql); - sql = "create table " + desTable_time_6 + " (c1 time(6) null);"; - stmt.execute(sql); - - String TVPCreateCmd = "CREATE TYPE " + tvp_varcharMax + " as table (c1 varchar(max) null)"; - stmt.executeUpdate(TVPCreateCmd); - - TVPCreateCmd = "CREATE TYPE " + tvp_time_6 + " as table (c1 time(6) null)"; - stmt.executeUpdate(TVPCreateCmd); - - createPreocedure(); - - populateCharSrcTable(); - populateTime6SrcTable(); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + + dropProcedure(); + + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_varcharMax) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax), stmt); + + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_time_6) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_time_6)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_time_6), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_time_6), stmt); + + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax) + + " (c1 varchar(max) null);"; + stmt.execute(sql); + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax) + + " (c1 varchar(max) null);"; + stmt.execute(sql); + + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6) + " (c1 time(6) null);"; + stmt.execute(sql); + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable_time_6) + " (c1 time(6) null);"; + stmt.execute(sql); + + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax) + + " as table (c1 varchar(max) null)"; + stmt.executeUpdate(TVPCreateCmd); + + TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvp_time_6) + + " as table (c1 time(6) null)"; + stmt.executeUpdate(TVPCreateCmd); + + createProcedure(); + + populateCharSrcTable(); + populateTime6SrcTable(); + } } private static void populateCharSrcTable() throws SQLException { - String sql = "insert into " + srcTable_varcharMax + " values (?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax) + " values (?)"; StringBuffer sb = new StringBuffer(); for (int i = 0; i < 4001; i++) { @@ -180,40 +195,49 @@ private static void populateCharSrcTable() throws SQLException { } private static void populateTime6SrcTable() throws SQLException { - String sql = "insert into " + srcTable_time_6 + " values ('2017-05-12 " + expectedTime6value + "')"; - connection.createStatement().execute(sql); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable_time_6) + + " values ('2017-05-12 " + expectedTime6value + "')"; + connection.createStatement().execute(sql); + } } private static void dropProcedure() throws SQLException { - TestUtils.dropProcedureIfExists(spName_varcharMax, stmt); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(spName_varcharMax), stmt); + } } - private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + spName_varcharMax + " @InputData " + tvp_varcharMax + " READONLY " + " AS " - + " BEGIN " + " INSERT INTO " + desTable_varcharMax + " SELECT * FROM @InputData" + " END"; + private static void createProcedure() throws SQLException { + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(spName_varcharMax) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax) + " READONLY " + " AS " + " BEGIN " + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax) + + " SELECT * FROM @InputData" + " END"; - stmt.execute(sql); + stmt.execute(sql); + } } @AfterAll public static void terminateVariation() throws SQLException { dropProcedure(); - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_varcharMax - + "') " + " drop type " + tvp_varcharMax); - TestUtils.dropTableIfExists(srcTable_varcharMax, stmt); - TestUtils.dropTableIfExists(desTable_varcharMax, stmt); - - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvp_time_6 - + "') " + " drop type " + tvp_time_6); - TestUtils.dropTableIfExists(srcTable_time_6, stmt); - TestUtils.dropTableIfExists(desTable_time_6, stmt); - - if (null != stmt) { - stmt.close(); - } - - if (null != connection) { - connection.close(); + try (Connection connection = DriverManager.getConnection(connectionString); + Statement stmt = connection.createStatement()) { + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_varcharMax) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_varcharMax)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_varcharMax), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_varcharMax), stmt); + + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvp_time_6) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvp_time_6)); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable_time_6), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable_time_6), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java index 1cfbeedc97..0cde147303 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPNumericTest.java @@ -6,6 +6,9 @@ import java.sql.SQLException; import java.sql.SQLTimeoutException; +import java.sql.Connection; +import java.sql.Statement; +import java.sql.DriverManager; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -13,27 +16,24 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBResultSet; -import com.microsoft.sqlserver.testframework.DBStatement; @RunWith(JUnitPlatform.class) public class TVPNumericTest extends AbstractTest { - private static DBConnection conn = null; - static DBStatement stmt = null; - static DBResultSet rs = null; static SQLServerDataTable tvp = null; static String expectecValue1 = "hello"; static String expectecValue2 = "world"; static String expectecValue3 = "again"; - private static String tvpName = "numericTVP"; - private static String charTable = "tvpNumericTable"; - private static String procedureName = "procedureThatCallsTVP"; + private static String tvpName; + private static String charTable; + private static String procedureName; /** * Test a previous failure regarding to numeric precision. Issue #211 @@ -49,8 +49,8 @@ public void testNumericPresicionIssue211() throws SQLException { tvp.addRow(12.12); tvp.addRow(1.123); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + charTable + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(charTable) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); @@ -59,8 +59,9 @@ public void testNumericPresicionIssue211() throws SQLException { @BeforeEach public void testSetup() throws SQLException { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); + tvpName = RandomUtil.getIdentifier("numericTVP"); + procedureName = RandomUtil.getIdentifier("procedureThatCallsTVP"); + charTable = RandomUtil.getIdentifier("tvpNumericTable"); dropProcedure(); dropTables(); @@ -72,48 +73,59 @@ public void testSetup() throws SQLException { } private void dropProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + procedureName - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + procedureName; - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(procedureName) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName); + stmt.execute(sql); + } } private static void dropTables() throws SQLException { - stmt.executeUpdate("if object_id('" + charTable + "','U') is not null" + " drop table " + charTable); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(charTable) + "','U') is not null" + + " drop table " + AbstractSQLGenerator.escapeIdentifier(charTable)); + } } private static void dropTVPS() throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); + } } private static void createPreocedure() throws SQLException { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " + " BEGIN " - + " INSERT INTO " + charTable + " SELECT * FROM @InputData" + " END"; - - stmt.execute(sql); + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " SELECT * FROM @InputData" + " END"; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTables() throws SQLException { - String sql = "create table " + charTable + " (c1 numeric(6,3) null);"; - stmt.execute(sql); + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (c1 numeric(6,3) null);"; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTVPS() throws SQLException { - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 numeric(6,3) null)"; - stmt.executeUpdate(TVPCreateCmd); + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + + " as table (c1 numeric(6,3) null)"; + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate(TVPCreateCmd); + } } @AfterEach public void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } + dropProcedure(); + dropTables(); + dropTVPS(); + if (null != tvp) { tvp.clear(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java index 0c522fdbdc..60f0223fe2 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPResultSetCursorTest.java @@ -17,14 +17,17 @@ import java.util.Properties; import java.util.TimeZone; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -42,10 +45,10 @@ public class TVPResultSetCursorTest extends AbstractTest { static String[] expectedTimestampStrings = {"2015-06-03 13:35:33.4610000", "2442-09-19 01:59:43.9990000", "2017-04-02 08:58:53.0000000"}; - private static String tvpName = "TVPResultSetCursorTest_TVP"; - private static String procedureName = "TVPResultSetCursorTest_SP"; - private static String srcTable = "TVPResultSetCursorTest_SourceTable"; - private static String desTable = "TVPResultSetCursorTest_DestinationTable"; + private static String tvpName = RandomUtil.getIdentifier("TVPResultSetCursorTest_TVP"); + private static String procedureName = RandomUtil.getIdentifier("TVPResultSetCursorTest_SP"); + private static String srcTable = RandomUtil.getIdentifier("TVPResultSetCursorTest_SourceTable"); + private static String desTable = RandomUtil.getIdentifier("TVPResultSetCursorTest_DestinationTable"); /** * Test a previous failure when using server cursor and using the same connection to create TVP and result set. @@ -72,10 +75,10 @@ private void serverCursorsTest(int resultSetType, int resultSetConcurrency) thro populateSourceTable(); try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency) - .executeQuery("select * from " + srcTable); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length); @@ -104,10 +107,11 @@ public void testSelectMethodSetToCursor() throws SQLException { populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + try (ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length); @@ -134,14 +138,15 @@ public void testSelectMethodSetToCursorWithSP() throws SQLException { createTVPS(); createTables(); - createPreocedure(); + createProcedure(); populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + try (ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn - .prepareCall("{call " + procedureName + "(?)}")) { - pstmt.setStructured(1, tvpName, rs); + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); @@ -172,9 +177,10 @@ public void testInvalidTVPName() throws SQLException { populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { + try (ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { pstmt.setStructured(1, "invalid" + tvpName, rs); @@ -205,13 +211,14 @@ public void testInvalidStoredProcedureName() throws SQLException { createTVPS(); createTables(); - createPreocedure(); + createProcedure(); populateSourceTable(); - try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn - .prepareCall("{call invalid" + procedureName + "(?)}")) { + try (ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); + SQLServerCallableStatement pstmt = (SQLServerCallableStatement) conn.prepareCall( + "{call invalid" + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}")) { pstmt.setStructured(1, tvpName, rs); pstmt.execute(); @@ -244,34 +251,35 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { populateSourceTable(); try (Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable)) { + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable))) { - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length); rs.beforeFirst(); } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length * 2); rs.beforeFirst(); } - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length * 3); } - String sql = "insert into " + desTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(desTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { for (int i = 0; i < expectedBigDecimals.length; i++) { @@ -284,10 +292,12 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { verifyDestinationTableData(expectedBigDecimals.length * 4); } } - try (ResultSet rs = stmt.executeQuery("select * from " + srcTable); + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(srcTable)); SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn - .prepareStatement("INSERT INTO " + desTable + " select * from ? ;")) { - pstmt.setStructured(1, tvpName, rs); + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + + " select * from ? ;")) { + pstmt.setStructured(1, AbstractSQLGenerator.escapeIdentifier(tvpName), rs); pstmt.execute(); verifyDestinationTableData(expectedBigDecimals.length * 5); } @@ -297,7 +307,8 @@ public void testMultiplePreparedStatementAndResultSet() throws SQLException { private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); - ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + ResultSet rs = conn.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(desTable))) { int expectedArrayLength = expectedBigDecimals.length; @@ -319,7 +330,7 @@ private static void verifyDestinationTableData(int expectedNumberOfRows) throws } private static void populateSourceTable() throws SQLException { - String sql = "insert into " + srcTable + " values (?,?,?,?)"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " values (?,?,?,?)"; Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); @@ -338,18 +349,18 @@ private static void populateSourceTable() throws SQLException { private static void dropTables() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - TestUtils.dropTableIfExists(srcTable, stmt); - TestUtils.dropTableIfExists(desTable, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(srcTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(desTable), stmt); } } private static void createTables() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String sql = "create table " + srcTable + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(srcTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); - sql = "create table " + desTable + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(desTable) + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } @@ -357,7 +368,7 @@ private static void createTables() throws SQLException { private static void createTVPS() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String TVPCreateCmd = "CREATE TYPE " + tvpName + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000) null)"; stmt.execute(TVPCreateCmd); } @@ -365,23 +376,33 @@ private static void createTVPS() throws SQLException { private static void dropTVPS() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - stmt.execute("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName + "') " - + " drop type " + tvpName); + stmt.execute("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); } } private static void dropProcedure() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - TestUtils.dropProcedureIfExists(procedureName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); } } - private static void createPreocedure() throws SQLException { + private static void createProcedure() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " - + " BEGIN " + " INSERT INTO " + desTable + " SELECT * FROM @InputData" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(desTable) + " SELECT * FROM @InputData" + + " END"; stmt.execute(sql); } } + + @AfterAll + public static void terminate() throws SQLException { + dropProcedure(); + dropTVPS(); + dropTables(); + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java index 4abf1bc12e..a375fe044d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPSchemaTest.java @@ -7,7 +7,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.Statement; +import java.sql.ResultSet; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -16,30 +20,27 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; -import com.microsoft.sqlserver.testframework.DBConnection; -import com.microsoft.sqlserver.testframework.DBResultSet; -import com.microsoft.sqlserver.testframework.DBStatement; @RunWith(JUnitPlatform.class) public class TVPSchemaTest extends AbstractTest { - private static DBConnection conn = null; - static DBStatement stmt = null; - static DBResultSet rs = null; static SQLServerDataTable tvp = null; static String expectecValue1 = "hello"; static String expectecValue2 = "world"; static String expectecValue3 = "again"; - private static String schemaName = "anotherSchma"; - private static String tvpNameWithouSchema = "charTVP"; - private static String tvpNameWithSchema = "[" + schemaName + "].[" + tvpNameWithouSchema + "]"; - private static String charTable = "[" + schemaName + "].[tvpCharTable]"; - private static String procedureName = "[" + schemaName + "].[procedureThatCallsTVP]"; + private static String schemaName; + private static String tvpNameWithouSchema; + private static String tvpNameWithSchema; + private static String charTable; + private static String procedureName; /** * PreparedStatement with storedProcedure @@ -52,12 +53,14 @@ public void testTVPSchemaPreparedStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - try (SQLServerPreparedStatement P_C_statement = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerPreparedStatement P_C_statement = (SQLServerPreparedStatement) conn.prepareStatement(sql); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_statement.setStructured(1, tvpNameWithSchema, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); + } } @@ -72,11 +75,12 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException final String sql = "{call " + procedureName + "(?)}"; - try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) conn.prepareCall(sql); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_statement.setStructured(1, tvpNameWithSchema, tvp); P_C_statement.execute(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); } } @@ -91,12 +95,13 @@ public void testTVPSchemaCallableStatementStoredProcedure() throws SQLException @DisplayName("TVPSchemaPreparedInsertCommand") public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOException { - try (SQLServerPreparedStatement P_C_stmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + charTable + " select * from ? ;")) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerPreparedStatement P_C_stmt = (SQLServerPreparedStatement) conn + .prepareStatement("INSERT INTO " + charTable + " select * from ? ;"); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); P_C_stmt.executeUpdate(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); } } @@ -111,20 +116,28 @@ public void testTVPSchemaPreparedInsertCommand() throws SQLException, IOExceptio @DisplayName("TVPSchemaCallableInsertCommand()") public void testTVPSchemaCallableInsertCommand() throws SQLException, IOException { - try (SQLServerCallableStatement P_C_stmt = (SQLServerCallableStatement) connection - .prepareCall("INSERT INTO " + charTable + " select * from ? ;")) { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); + SQLServerCallableStatement P_C_stmt = (SQLServerCallableStatement) conn + .prepareCall("INSERT INTO " + charTable + " select * from ? ;"); + ResultSet rs = stmt.executeQuery("select * from " + charTable)) { P_C_stmt.setStructured(1, tvpNameWithSchema, tvp); P_C_stmt.executeUpdate(); - rs = stmt.executeQuery("select * from " + charTable); verify(rs); } } @BeforeEach public void testSetup() throws SQLException { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); + schemaName = RandomUtil.getIdentifier("anotherSchema"); + tvpNameWithouSchema = RandomUtil.getIdentifier("charTVP"); + tvpNameWithSchema = AbstractSQLGenerator.escapeIdentifier(schemaName) + "." + + AbstractSQLGenerator.escapeIdentifier(tvpNameWithouSchema); + + charTable = AbstractSQLGenerator.escapeIdentifier(schemaName) + "." + + AbstractSQLGenerator.escapeIdentifier("tvpCharTable"); + procedureName = AbstractSQLGenerator.escapeIdentifier(schemaName) + "." + + AbstractSQLGenerator.escapeIdentifier("procedureThatCallsTVP"); dropProcedure(); dropTables(); @@ -148,7 +161,7 @@ public void testSetup() throws SQLException { tvp.addRow(expectecValue1, expectecValue2, expectecValue3); } - private void verify(DBResultSet rs) throws SQLException { + private void verify(ResultSet rs) throws SQLException { while (rs.next()) { String actualValue1 = rs.getString(1); String actualValue2 = rs.getString(2); @@ -161,58 +174,71 @@ private void verify(DBResultSet rs) throws SQLException { } private void dropProcedure() throws SQLException { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + procedureName - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + procedureName; - stmt.execute(sql); + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(procedureName) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + procedureName; + + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private static void dropTables() throws SQLException { - stmt.executeUpdate("if object_id('" + charTable + "','U') is not null" + " drop table " + charTable); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(charTable) + "','U') is not null" + + " drop table " + charTable); + } } private static void dropTVPS() throws SQLException { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" - + tvpNameWithouSchema + "') " + " drop type " + tvpNameWithSchema); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpNameWithouSchema) + "') " + " drop type " + tvpNameWithSchema); + } } private static void dropAndCreateSchema() throws SQLException { - stmt.execute("if EXISTS (SELECT * FROM sys.schemas where name = 'anotherSchma') drop schema anotherSchma"); - stmt.execute("CREATE SCHEMA anotherSchma"); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute( + "if EXISTS (SELECT * FROM sys.schemas where name = '" + TestUtils.escapeSingleQuotes(schemaName) + + "') drop schema " + AbstractSQLGenerator.escapeIdentifier(schemaName)); + stmt.execute("CREATE SCHEMA " + AbstractSQLGenerator.escapeIdentifier(schemaName)); + } } private static void createPreocedure() throws SQLException { String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpNameWithSchema + " READONLY " + " AS " + " BEGIN " + " INSERT INTO " + charTable + " SELECT * FROM @InputData" + " END"; - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTables() throws SQLException { String sql = "create table " + charTable + " (" + "PlainChar char(50) null," + "PlainVarchar varchar(50) null," + "PlainVarcharMax varchar(max) null," + ");"; - stmt.execute(sql); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.execute(sql); + } } private void createTVPS() throws SQLException { String TVPCreateCmd = "CREATE TYPE " + tvpNameWithSchema + " as table ( " + "PlainChar char(50) null," + "PlainVarchar varchar(50) null," + "PlainVarcharMax varchar(max) null" + ")"; - stmt.executeUpdate(TVPCreateCmd); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + stmt.executeUpdate(TVPCreateCmd); + } } @AfterEach public void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - if (null != rs) { - rs.close(); - } + dropProcedure(); + dropTables(); + dropTVPS(); + if (null != tvp) { tvp.clear(); } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java index 260c139740..d48f3bb575 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/tvp/TVPTypesTest.java @@ -21,10 +21,13 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerResultSet; +import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -32,9 +35,9 @@ public class TVPTypesTest extends AbstractTest { static SQLServerDataTable tvp = null; - private static String tvpName = "TVP"; - private static String table = "TVPTable"; - private static String procedureName = "procedureThatCallsTVP"; + private static String tvpName; + private static String tableName; + private static String procedureName; private String value = null; /** @@ -56,14 +59,15 @@ public void testLongVarchar() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -90,15 +94,15 @@ public void testLongNVarchar() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection conn = DriverManager.getConnection(connectionString); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + Statement stmt = conn.createStatement(); ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(rs.getString(1), value); } @@ -123,14 +127,15 @@ public void testXML() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.SQLXML); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -154,14 +159,15 @@ public void testnText() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -185,14 +191,15 @@ public void testText() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -216,14 +223,15 @@ public void testImage() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARBINARY); tvp.addRow(value.getBytes()); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertTrue(parseByte(rs.getBytes(1), value.getBytes())); @@ -251,14 +259,15 @@ public void testTVPLongVarcharStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -284,14 +293,15 @@ public void testTVPLongNVarcharStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(buffer.toString()); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -317,14 +327,15 @@ public void testTVPXMLStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.SQLXML); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -351,14 +362,15 @@ public void testTVPTextStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARCHAR); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -385,14 +397,15 @@ public void testTVPNTextStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGNVARCHAR); tvp.addRow(value); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertEquals(rs.getString(1), value); } @@ -419,14 +432,15 @@ public void testTVPImageStoredProcedure() throws SQLException { tvp.addColumnMetadata("c1", java.sql.Types.LONGVARBINARY); tvp.addRow(value.getBytes()); - final String sql = "{call " + procedureName + "(?)}"; + final String sql = "{call " + AbstractSQLGenerator.escapeIdentifier(procedureName) + "(?)}"; try (SQLServerCallableStatement P_C_statement = (SQLServerCallableStatement) connection.prepareCall(sql)) { P_C_statement.setStructured(1, tvpName, tvp); P_C_statement.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) assertTrue(parseByte(rs.getBytes(1), value.getBytes())); } @@ -449,14 +463,15 @@ public void testDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.DATETIME); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(((SQLServerResultSet) rs).getDateTime(1), value); } @@ -481,14 +496,15 @@ public void testSmallDateTime() throws SQLException { tvp.addColumnMetadata("c1", microsoft.sql.Types.SMALLDATETIME); tvp.addRow(value); - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection - .prepareStatement("INSERT INTO " + table + " select * from ? ;")) { + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " select * from ? ;")) { pstmt.setStructured(1, tvpName, tvp); pstmt.execute(); try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - ResultSet rs = stmt.executeQuery("select * from " + table)) { + ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) { assertEquals(((SQLServerResultSet) rs).getSmallDateTime(1), returnValue); } @@ -498,6 +514,10 @@ public void testSmallDateTime() throws SQLException { @BeforeEach public void testSetup() throws SQLException { + tvpName = RandomUtil.getIdentifier("TVP"); + tableName = RandomUtil.getIdentifier("TVPTable"); + procedureName = RandomUtil.getIdentifier("procedureThatCallsTVP"); + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { dropProcedure(); dropTables(); @@ -516,43 +536,50 @@ public static void terminate() throws SQLException { private static void dropProcedure() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + procedureName - + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + procedureName; + String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + + TestUtils.escapeSingleQuotes(procedureName) + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + + " DROP PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName); stmt.execute(sql); } } private static void dropTables() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - stmt.executeUpdate("if object_id('" + table + "','U') is not null" + " drop table " + table); + stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(tableName) + "','U') is not null" + + " drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } private static void dropTVPS() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + tvpName - + "') " + " drop type " + tvpName); + stmt.executeUpdate("IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = '" + + TestUtils.escapeSingleQuotes(tvpName) + "') " + " drop type " + + AbstractSQLGenerator.escapeIdentifier(tvpName)); } } private static void createPreocedure() throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String sql = "CREATE PROCEDURE " + procedureName + " @InputData " + tvpName + " READONLY " + " AS " - + " BEGIN " + " INSERT INTO " + table + " SELECT * FROM @InputData" + " END"; + String sql = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " @InputData " + + AbstractSQLGenerator.escapeIdentifier(tvpName) + " READONLY " + " AS " + " BEGIN " + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SELECT * FROM @InputData" + + " END"; stmt.execute(sql); } } private void createTables(String colType) throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String sql = "create table " + table + " (c1 " + colType + " null);"; + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1 " + colType + + " null);"; stmt.execute(sql); } } private void createTVPS(String colType) throws SQLException { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - String TVPCreateCmd = "CREATE TYPE " + tvpName + " as table (c1 " + colType + " null)"; + String TVPCreateCmd = "CREATE TYPE " + AbstractSQLGenerator.escapeIdentifier(tvpName) + " as table (c1 " + + colType + " null)"; stmt.executeUpdate(TVPCreateCmd); } } @@ -568,6 +595,10 @@ private boolean parseByte(byte[] expectedData, byte[] retrieved) { @AfterEach public void terminateVariation() throws SQLException { + dropProcedure(); + dropTables(); + dropTVPS(); + if (null != tvp) { tvp.clear(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/SavepointTest.java similarity index 98% rename from src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java rename to src/test/java/com/microsoft/sqlserver/jdbc/unit/SavepointTest.java index 43b618c769..aea5689d3a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/TestSavepoint.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/SavepointTest.java @@ -27,7 +27,7 @@ * Unit test case for Creating SavePoint. */ @RunWith(JUnitPlatform.class) -public class TestSavepoint extends AbstractTest { +public class SavepointTest extends AbstractTest { String savePointName = RandomUtil.getIdentifier("SavePoint", 31, true, false); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java index df8214b3eb..2287856592 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/UTF8SupportTest.java @@ -110,7 +110,7 @@ public static void setUp() throws ClassNotFoundException, SQLException { connection = PrepUtil.getConnection(getConfiguredProperty("mssql_jdbc_test_connection_properties")); if (TestUtils.serverSupportsUTF8(connection)) { databaseName = RandomUtil.getIdentifier("UTF8Database"); - tableName = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("RequestBoundaryTable")); + tableName = RandomUtil.getIdentifier("RequestBoundaryTable"); createDatabaseWithUTF8Collation(); connection.setCatalog(databaseName); } @@ -137,20 +137,23 @@ private static void createDatabaseWithUTF8Collation() throws SQLException { private static void createTable(String columnType) throws SQLException { try (Statement stmt = connection.createStatement();) { - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate("CREATE TABLE " + tableName + " (c " + columnType + ")"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate( + "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c " + columnType + ")"); } } public void clearTable() throws SQLException { try (Statement stmt = connection.createStatement();) { - stmt.executeUpdate("DELETE FROM " + tableName); + stmt.executeUpdate("DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } public void validate(String value) throws SQLException { - try (PreparedStatement psInsert = connection.prepareStatement("INSERT INTO " + tableName + " VALUES(?)"); - PreparedStatement psFetch = connection.prepareStatement("SELECT * FROM " + tableName); + try (PreparedStatement psInsert = connection + .prepareStatement("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES(?)"); + PreparedStatement psFetch = connection + .prepareStatement("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName)); Statement stmt = connection.createStatement();) { clearTable(); // Used for exact byte comparison. @@ -160,7 +163,8 @@ public void validate(String value) throws SQLException { psInsert.executeUpdate(); // Fetch using Statement. - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); // Compare Strings. assertEquals(value, rs.getString(1)); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java index 55e8e15768..f537c16571 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsStreamingTest.java @@ -26,6 +26,7 @@ import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -81,7 +82,8 @@ private String getStringFromReader(Reader r, long l) throws IOException { private void createLobTable(Statement stmt, String table, Lob l) throws SQLException { String columnType = (l == Lob.CLOB) ? "varchar(max)" : "nvarchar(max)"; - stmt.execute("CREATE TABLE [" + table + "] (id int, lobValue " + columnType + ")"); + stmt.execute("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table) + " (id int, lobValue " + columnType + + ")"); } private ArrayList createRandomStringArray(Lob l) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsTest.java similarity index 96% rename from src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/lobsTest.java rename to src/test/java/com/microsoft/sqlserver/jdbc/unit/lobs/LobsTest.java index 68cd41d7be..4ec087e167 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 @@ -59,7 +59,7 @@ * */ @RunWith(JUnitPlatform.class) -public class lobsTest extends AbstractTest { +public class LobsTest extends AbstractTest { static Connection conn = null; static Statement stmt = null; static String tableName; @@ -207,11 +207,7 @@ else if (lobClass == Blob.class) } if (!verified) { // Odd CharacterStream length will throw this exception - if (!e.getMessage().contains(TestResource.getResource("R_badStreamLength"))) - - { - if (lobClass == DBCharacterStream.class || lobClass == DBBinaryStream.class) - assertTrue(e.getSQLState() != null, TestResource.getResource("R_SQLStateNull")); + if (!e.getMessage().contains(TestResource.getResource("R_badStreamLength"))) { assertTrue(e.getMessage().contains(TestResource.getResource("R_streamReadError"))); } @@ -323,23 +319,20 @@ private void testMultipleClose(Class streamClass) throws Exception { continue; } - Object stream = null; - try { - stream = rs.getXXX(i + 1, streamClass); - } finally { - if (null == stream) { - assertEquals(stream, rs.getObject(i + 1), TestResource.getResource("R_streamNull")); - } else { - // close the stream twice - if (streamClass == DBCharacterStream.class) { - ((Reader) stream).close(); - ((Reader) stream).close(); - } else { - ((InputStream) stream).close(); - ((InputStream) stream).close(); + if (streamClass == DBCharacterStream.class) { + try (Reader stream = (Reader) rs.getXXX(i + 1, streamClass)) { + if (null == stream) { + assertEquals(stream, rs.getObject(i + 1), + TestResource.getResource("R_streamNull")); + } + } + } else { + try (InputStream stream = (InputStream) rs.getXXX(i + 1, streamClass)) { + if (null == stream) { + assertEquals(stream, rs.getObject(i + 1), + TestResource.getResource("R_streamNull")); } } - } } } @@ -589,6 +582,7 @@ public void readMultipleBlobStreamsThenCloseRS() throws Exception { if (null != stream) { stream.close(); } + dropTables(table); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java index 53b8856510..7d14a67ab0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecuteWithErrorsTest.java @@ -44,12 +44,13 @@ public class BatchExecuteWithErrorsTest extends AbstractTest { public static final Logger log = Logger.getLogger("BatchExecuteWithErrors"); Connection con = null; - String tableN = RandomUtil.getIdentifier("t_Repro47239"); - final String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); - final String insertStmt = "INSERT INTO " + tableName + " VALUES (999, 'HELLO', '4/12/1994')"; + final String tableName = RandomUtil.getIdentifier("t_Repro47239"); + final String insertStmt = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (999, 'HELLO', '4/12/1994')"; final String error16 = "RAISERROR ('raiserror level 16',16,42)"; final String select = "SELECT 1"; - final String dateConversionError = "insert into " + tableName + " values (999999, 'Hello again', 'asdfasdf')"; + final String dateConversionError = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " values (999999, 'Hello again', 'asdfasdf')"; /** * Batch test @@ -86,12 +87,13 @@ public void Repro47239largeUseBulkCopyAPI() throws Exception { } private void Repro47239Internal(String mode) throws Exception { - String tableN = RandomUtil.getIdentifier("t_Repro47239"); - final String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); - final String insertStmt = "INSERT INTO " + tableName + " VALUES (999, 'HELLO', '4/12/1994')"; + final String tableName = RandomUtil.getIdentifier("t_Repro47239"); + final String insertStmt = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (999, 'HELLO', '4/12/1994')"; final String error16 = "RAISERROR ('raiserror level 16',16,42)"; final String select = "SELECT 1"; - final String dateConversionError = "insert into " + tableName + " values (999999, 'Hello again', 'asdfasdf')"; + final String dateConversionError = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " values (999999, 'Hello again', 'asdfasdf')"; String warning; String error; @@ -139,9 +141,9 @@ private void Repro47239Internal(String mode) throws Exception { try (Statement stmt = conn.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (Exception ignored) {} - stmt.executeUpdate("create table " + tableName + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1_int int, c2_varchar varchar(20), c3_date datetime, c4_int int identity(1,1) primary key)"); // Regular Statement batch update @@ -299,7 +301,7 @@ private void Repro47239Internal(String mode) throws Exception { } finally { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { - stmt.executeUpdate("drop table " + tableName); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } } } @@ -352,10 +354,10 @@ private void Repro47239largeInternal(String mode) throws Exception { try (Statement stmt = conn.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (Exception ignored) {} try { - stmt.executeLargeUpdate("create table " + tableName + stmt.executeLargeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (c1_int int, c2_varchar varchar(20), c3_date datetime, c4_int int identity(1,1) primary key)"); } catch (Exception ignored) {} // Regular Statement batch update @@ -505,7 +507,7 @@ private void Repro47239largeInternal(String mode) throws Exception { } try { - stmt.executeLargeUpdate("drop table " + tableName); + stmt.executeLargeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(tableName)); } catch (Exception ignored) {} } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java index a0e2c4428c..42b5ef89bc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchExecutionTest.java @@ -23,10 +23,12 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; @@ -38,6 +40,9 @@ @RunWith(JUnitPlatform.class) public class BatchExecutionTest extends AbstractTest { + static String ctstable1; + static String ctstable2; + /** * testAddBatch1 and testExecutionBatch one looks similar except for the parameters being passed for select query. * TODO: we should look and simply the test later by parameterized values @@ -82,7 +87,8 @@ private void testExecuteBatch1Internal(String mode) { int updateCountlen = 0; try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { - String sPrepStmt = "update ctstable2 set PRICE=PRICE*20 where TYPE_ID=?"; + String sPrepStmt = "update " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " set PRICE=PRICE*20 where TYPE_ID=?"; if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI((SQLServerConnection) connection); @@ -105,7 +111,8 @@ private void testExecuteBatch1Internal(String mode) { assertTrue(updateCountlen == 3, TestResource.getResource("R_executeBatchFailed") + ": " + TestResource.getResource("R_incorrectUpdateCount")); - String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; + String sPrepStmt1 = "select count(*) from " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " where TYPE_ID=?"; try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1)) { for (int n = 1; n <= 3; n++) { @@ -133,23 +140,30 @@ private static void createTable() throws SQLException { try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - String sql1 = "create table ctstable1 (TYPE_ID int, TYPE_DESC varchar(32), primary key(TYPE_ID)) "; - String sql2 = "create table ctstable2 (KEY_ID int, COF_NAME varchar(32), PRICE float, TYPE_ID int, primary key(KEY_ID), foreign key(TYPE_ID) references ctstable1) "; + String sql1 = "create table " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + + " (TYPE_ID int, TYPE_DESC varchar(32), primary key(TYPE_ID)) "; + String sql2 = "create table " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " (KEY_ID int, COF_NAME varchar(32), PRICE float, TYPE_ID int, primary key(KEY_ID), foreign key(TYPE_ID) references " + + AbstractSQLGenerator.escapeIdentifier(ctstable1) + ")"; stmt.execute(sql1); stmt.execute(sql2); - String sqlin2 = "insert into ctstable1 values (1,'COFFEE-Desc')"; + String sqlin2 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + + " values (1,'COFFEE-Desc')"; stmt.execute(sqlin2); - sqlin2 = "insert into ctstable1 values (2,'COFFEE-Desc2')"; + sqlin2 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + " values (2,'COFFEE-Desc2')"; stmt.execute(sqlin2); - sqlin2 = "insert into ctstable1 values (3,'COFFEE-Desc3')"; + sqlin2 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable1) + " values (3,'COFFEE-Desc3')"; stmt.execute(sqlin2); - String sqlin1 = "insert into ctstable2 values (9,'COFFEE-9',9.0, 1)"; + String sqlin1 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " values (9,'COFFEE-9',9.0, 1)"; stmt.execute(sqlin1); - sqlin1 = "insert into ctstable2 values (10,'COFFEE-10',10.0, 2)"; + sqlin1 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " values (10,'COFFEE-10',10.0, 2)"; stmt.execute(sqlin1); - sqlin1 = "insert into ctstable2 values (11,'COFFEE-11',11.0, 3)"; + sqlin1 = "insert into " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " values (11,'COFFEE-11',11.0, 3)"; stmt.execute(sqlin1); } } @@ -159,7 +173,8 @@ private void testAddBatch1Internal(String mode) { int retValue[] = {0, 0, 0}; try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;");) { - String sPrepStmt = "update ctstable2 set PRICE=PRICE*20 where TYPE_ID=?"; + String sPrepStmt = "update " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " set PRICE=PRICE*20 where TYPE_ID=?"; if (mode.equalsIgnoreCase("bulkcopy")) { modifyConnectionForBulkCopyAPI((SQLServerConnection) connection); @@ -181,7 +196,8 @@ private void testAddBatch1Internal(String mode) { assertTrue(updateCountlen == 3, TestResource.getResource("R_addBatchFailed") + ": " + TestResource.getResource("R_incorrectUpdateCount")); - String sPrepStmt1 = "select count(*) from ctstable2 where TYPE_ID=?"; + String sPrepStmt1 = "select count(*) from " + AbstractSQLGenerator.escapeIdentifier(ctstable2) + + " where TYPE_ID=?"; try (PreparedStatement pstmt1 = connection.prepareStatement(sPrepStmt1)) { @@ -217,6 +233,9 @@ private void modifyConnectionForBulkCopyAPI(SQLServerConnection con) throws Exce @BeforeAll public static void testSetup() throws TestAbortedException, Exception { + ctstable1 = RandomUtil.getIdentifier("ctstable1"); + ctstable2 = RandomUtil.getIdentifier("ctstable2"); + try (DBConnection con = new DBConnection(connectionString)) { assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); } @@ -229,13 +248,17 @@ private static void dropTable() throws SQLException { try (Connection connection = DriverManager .getConnection(connectionString + ";columnEncryptionSetting=Enabled;"); Statement stmt = (SQLServerStatement) connection.createStatement()) { - TestUtils.dropTableIfExists("ctstable2", stmt); - TestUtils.dropTableIfExists("ctstable1", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(ctstable2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(ctstable1), stmt); } } @AfterAll - public static void terminateVariation() throws SQLException { + public static void terminateVariation() throws Exception { + try (DBConnection con = new DBConnection(connectionString)) { + assumeTrue(13 <= con.getServerVersion(), TestResource.getResource("R_Incompat_SQLServerVersion")); + } + dropTable(); } } 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 60d279cf29..897c9ade39 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/BatchTriggerTest.java @@ -20,9 +20,11 @@ import org.junit.runner.RunWith; import org.opentest4j.TestAbortedException; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -33,10 +35,9 @@ @RunWith(JUnitPlatform.class) public class BatchTriggerTest extends AbstractTest { - static String tableName = "triggerTable"; - static String triggerName = "triggerTest"; - static String insertQuery = "insert into " + tableName - + " (col1, col2, col3, col4) values (1, '22-08-2017 17:30:00.000', 'R4760', 31)"; + static String tableName; + static String triggerName;; + static String insertQuery; /** * Tests that the proper trigger exception is thrown using statement @@ -83,9 +84,11 @@ public void preparedStatementTest() throws SQLException { private static void createTrigger(String triggerName) throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - String sql = "create trigger " + triggerName + " on " + tableName + " for insert " + "as " + "begin " - + "if (select col1 from " + tableName + ") > 10 " + "begin " + "return " + "end " + "RAISERROR ('" - + TestResource.getResource("R_customErrorMessage") + "', 16, 0) " + "rollback transaction " + "end"; + String sql = "create trigger " + triggerName + " on " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " for insert " + "as " + "begin " + "if (select col1 from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + ") > 10 " + "begin " + "return " + "end " + + "RAISERROR ('" + TestResource.getResource("R_customErrorMessage") + "', 16, 0) " + + "rollback transaction " + "end"; stmt.execute(sql); } } @@ -98,7 +101,8 @@ private static void createTrigger(String triggerName) throws SQLException { private static void createTable() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - String sql = "create table " + tableName + " ( col1 int, col2 varchar(50), col3 varchar(10), col4 int)"; + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ( col1 int, col2 varchar(50), col3 varchar(10), col4 int)"; stmt.execute(sql); } } @@ -111,14 +115,19 @@ private static void createTable() throws SQLException { */ @BeforeAll public static void testSetup() throws TestAbortedException, Exception { + tableName = RandomUtil.getIdentifier("triggerTable"); + triggerName = RandomUtil.getIdentifier("triggerTest"); + insertQuery = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1, col2, col3, col4) values (1, '22-08-2017 17:30:00.000', 'R4760', 31)"; + try (Connection connection = DriverManager.getConnection(connectionString); SQLServerStatement stmt = (SQLServerStatement) connection.createStatement()) { stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" - + " WHERE [type] = 'TR' AND [name] = '" + triggerName + "'\r\n" + " )\r\n" - + " DROP TRIGGER " + triggerName + ";"); + + " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n" + + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + ";"); dropTable(); createTable(); - createTrigger(triggerName); + createTrigger(AbstractSQLGenerator.escapeIdentifier(triggerName)); } } @@ -130,7 +139,7 @@ public static void testSetup() throws TestAbortedException, Exception { private static void dropTable() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } @@ -146,8 +155,8 @@ public static void terminateVariation() throws SQLException { dropTable(); stmt.execute("IF EXISTS (\r\n" + " SELECT *\r\n" + " FROM sys.objects\r\n" - + " WHERE [type] = 'TR' AND [name] = '" + triggerName + "'\r\n" + " )\r\n" - + " DROP TRIGGER " + triggerName + ";"); + + " WHERE [type] = 'TR' AND [name] = '" + TestUtils.escapeSingleQuotes(triggerName) + "'\r\n" + + " )\r\n" + " DROP TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + ";"); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java index 1aa0e28a15..ee98c17dc0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java @@ -31,10 +31,8 @@ */ @RunWith(JUnitPlatform.class) public class CallableMixedTest extends AbstractTest { - String tableN = RandomUtil.getIdentifier("TFOO3"); - String procN = RandomUtil.getIdentifier("SPFOO3"); - String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); - String procName = AbstractSQLGenerator.escapeIdentifier(procN); + String tableName = RandomUtil.getIdentifier("TFOO3"); + String procName = RandomUtil.getIdentifier("SPFOO3"); /** * Tests Callable mix @@ -47,16 +45,18 @@ public void datatypesTest() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement();) { - statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); - statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); + statement.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (c1_int int primary key, col2 int)"); + statement + .executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 1)"); - statement.executeUpdate("CREATE PROCEDURE " + procName + statement.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " - + tableName + + AbstractSQLGenerator.escapeIdentifier(tableName) + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - try (CallableStatement callableStatement = connection - .prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }")) { + try (CallableStatement callableStatement = connection.prepareCall( + "{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?, ?, ?, ?) }")) { callableStatement.registerOutParameter((int) 1, (int) 4); callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); callableStatement.registerOutParameter((int) 3, (int) 4); @@ -104,7 +104,7 @@ public void datatypesTest() throws SQLException { * @throws SQLException */ private void terminateVariation(Statement statement) throws SQLException { - TestUtils.dropTableIfExists(tableName, statement); - TestUtils.dropProcedureIfExists(procName, statement); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), statement); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), statement); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java index e94d42d2ae..bfd85ba6cc 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java @@ -27,8 +27,10 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -42,6 +44,13 @@ public class LimitEscapeTest extends AbstractTest { private static Vector offsetQuery = new Vector<>(); private static Connection conn = null; + // TODO: remove quote for now to avoid bug in driver + static String table1 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t1").replaceAll("\'", ""); + static String table2 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t2").replaceAll("\'", ""); + static String table3 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t3").replaceAll("\'", ""); + static String table4 = RandomUtil.getIdentifier("UnitStatement_LimitEscape_t4").replaceAll("\'", ""); + static String procName = RandomUtil.getIdentifier("UnitStatement_LimitEscape_p1").replaceAll("\'", ""); + static class Query { String inputSql, outputSql; int[] idCols = null; @@ -214,38 +223,45 @@ public static void createAndPopulateTables(Connection conn) throws Exception { // is done // around table names. try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t1"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table1)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t2"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table2)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t3"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table3)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop table UnitStatement_LimitEscape_t4"); + stmt.executeUpdate("drop table " + AbstractSQLGenerator.escapeIdentifier(table4)); } catch (Exception ex) {} ; try { - stmt.executeUpdate("drop procedure UnitStatement_LimitEscape_p1"); + stmt.executeUpdate("drop procedure " + AbstractSQLGenerator.escapeIdentifier(procName)); } catch (Exception ex) {} ; - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t1 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t2 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t3 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - stmt.executeUpdate( - "create table UnitStatement_LimitEscape_t4 (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); - - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t1 values " + "(1, 1, 'col3', 'col4'), " + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table1) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table2) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table3) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(table4) + + " (col1 int, col2 int, col3 varchar(100), col4 varchar(100), id int identity(1,1) primary key)"); + + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table1) + " values " + + "(1, 1, 'col3', 'col4'), " + "(2, 2, 'row2 '' with '' quote', 'row2 with limit {limit 22} {limit ?}')," + "(3, 3, 'row3 with subquery (select * from t1)', 'row3 with subquery (select * from (select * from t1) {limit 4})')," + "(4, 4, 'select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)')," + "(5, 5, 'openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')')"); - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t2 values (11, 11, 'col33', 'col44')"); - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t3 values (111, 111, 'col333', 'col444')"); - stmt.executeUpdate("Insert into UnitStatement_LimitEscape_t4 values (1111, 1111, 'col4444', 'col4444')"); - String query = "create procedure UnitStatement_LimitEscape_p1 @col3Value varchar(512), @col4Value varchar(512) AS BEGIN SELECT TOP 1 * from UnitStatement_LimitEscape_t1 where col3 = @col3Value and col4 = @col4Value END"; + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table2) + + " values (11, 11, 'col33', 'col44')"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table3) + + " values (111, 111, 'col333', 'col444')"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(table4) + + " values (1111, 1111, 'col4444', 'col4444')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value varchar(512), @col4Value varchar(512) AS BEGIN SELECT TOP 1 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = @col3Value and col4 = @col4Value END"; stmt.execute(query); } } @@ -261,8 +277,8 @@ public void initAndVerifyQueries() throws Exception { Query qry; // 1 // Test whether queries without limit syntax works - qry = new Query("select TOP 1 * from UnitStatement_LimitEscape_t1", - "select TOP 1 * from UnitStatement_LimitEscape_t1", 1, // # of rows + qry = new Query("select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1), + "select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -271,8 +287,8 @@ public void initAndVerifyQueries() throws Exception { // 2 // Test parentheses in limit syntax - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit ( ( (2)))}", - "select TOP ( ( (2))) * from UnitStatement_LimitEscape_t1", 2, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit ( ( (2)))}", + "select TOP ( ( (2))) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 2, // # of rows 5, // # of columns new int[] {1, 2}, // id column values new int[][] {{1, 1}, {2, 2}}, // int column values @@ -283,9 +299,10 @@ public void initAndVerifyQueries() throws Exception { // 3 // Test limit syntax in string literal as well as in query, also test subquery syntax in string literal - qry = new Query( - "select ( (col1)), ( ((col2) ) ) from UnitStatement_LimitEscape_t1 where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})' {limit (35)}", - "select TOP (35) ( (col1)), ( ((col2) ) ) from UnitStatement_LimitEscape_t1 where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})'", + qry = new Query("select ( (col1)), ( ((col2) ) ) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})' {limit (35)}", + "select TOP (35) ( (col1)), ( ((col2) ) ) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'row3 with subquery (select * from t1)' and col4 = 'row3 with subquery (select * from (select * from t1) {limit 4})'", 1, // # of rows 2, // # of columns new int[] {3}, // id column values @@ -295,9 +312,10 @@ public void initAndVerifyQueries() throws Exception { // 4 // Test quotes/limit syntax/scalar function in string literal. Also test real limit syntax in query. - qry = new Query( - "select (col1), (col2) from UnitStatement_LimitEscape_t1 where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)' {limit 3543}", - "select TOP 3543 (col1), (col2) from UnitStatement_LimitEscape_t1 where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)'", + qry = new Query("select (col1), (col2) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)' {limit 3543}", + "select TOP 3543 (col1), (col2) from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'select * from t1 {limit 4} ''quotes'' (braces)' and col4 = 'ucase(scalar function)'", 1, // # of rows 2, // # of columns new int[] {4}, // id column values @@ -307,9 +325,10 @@ public void initAndVerifyQueries() throws Exception { // 5 // Test openquery/openrowset in string literals - qry = new Query( - "select col1 from UnitStatement_LimitEscape_t1 where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')' {limit (((2)))}", - "select TOP (((2))) col1 from UnitStatement_LimitEscape_t1 where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')'", + qry = new Query("select col1 from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')' {limit (((2)))}", + "select TOP (((2))) col1 from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " where col3 = 'openquery(''server'', ''query'')' and col4 = 'openrowset(''server'',''connection string'',''query'')'", 1, // # of rows 1, // # of columns new int[] {5}, // id column values @@ -319,8 +338,12 @@ public void initAndVerifyQueries() throws Exception { // 6 // Test limit syntax in subquery as well as in outer query - qry = new Query("select id from (select * from UnitStatement_LimitEscape_t1 {limit 10}) t1 {limit ((1) )}", - "select TOP ((1) ) id from (select TOP 10 * from UnitStatement_LimitEscape_t1) t1", 1, // # of rows + qry = new Query( + "select id from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 10}) t1 {limit ((1) )}", + "select TOP ((1) ) id from (select TOP 10 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ") t1", + 1, // # of rows 1, // # of columns new int[] {1}, // id column values null, // int column values @@ -330,9 +353,12 @@ public void initAndVerifyQueries() throws Exception { // 7 // Test multiple parentheses in limit syntax and in subquery qry = new Query( - "select id from (( (select * from UnitStatement_LimitEscape_t1 {limit 10})) ) t1 {limit ((1) )}", - "select TOP ((1) ) id from (( (select TOP 10 * from UnitStatement_LimitEscape_t1)) ) t1", 1, // # of - // rows + "select id from (( (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 10})) ) t1 {limit ((1) )}", + "select TOP ((1) ) id from (( (select TOP 10 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ")) ) t1", + 1, // # of + // rows 1, // # of columns new int[] {1}, // id column values null, // int column values @@ -342,8 +368,12 @@ public void initAndVerifyQueries() throws Exception { // 8 // Test limit syntax in multiple subqueries, also test arbitrary spaces in limit syntax qry = new Query( - "select j1.id from (( (select * from UnitStatement_LimitEscape_t1 {limit 10})) ) j1 join (select * from UnitStatement_LimitEscape_t2 {limit 4}) j2 on j1.id = j2.id {limit (1)}", - "select TOP (1) j1.id from (( (select TOP 10 * from UnitStatement_LimitEscape_t1)) ) j1 join (select TOP 4 * from UnitStatement_LimitEscape_t2) j2 on j1.id = j2.id", + "select j1.id from (( (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 10})) ) j1 join (select * from " + AbstractSQLGenerator.escapeIdentifier(table2) + + " {limit 4}) j2 on j1.id = j2.id {limit (1)}", + "select TOP (1) j1.id from (( (select TOP 10 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ")) ) j1 join (select TOP 4 * from " + AbstractSQLGenerator.escapeIdentifier(table2) + + ") j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -354,8 +384,12 @@ public void initAndVerifyQueries() throws Exception { // 9 // Test limit syntax in multiple levels of nested subqueries qry = new Query( - "select j1.id from (select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}) j1 join (select * from UnitStatement_LimitEscape_t2 {limit 4}) j2 on j1.id = j2.id {limit 1}", - "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3) j1 join (select TOP 4 * from UnitStatement_LimitEscape_t2) j2 on j1.id = j2.id", + "select j1.id from (select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}) j1 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table2) + " {limit 4}) j2 on j1.id = j2.id {limit 1}", + "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + ") j3) j1 join (select TOP 4 * from " + + AbstractSQLGenerator.escapeIdentifier(table2) + ") j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -366,8 +400,16 @@ public void initAndVerifyQueries() throws Exception { // 10 // Test limit syntax in multiple levels of nested subqueries as well as in outer query qry = new Query( - "select j1.id from (select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from UnitStatement_LimitEscape_t3 {limit 5}) j4 join (select * from UnitStatement_LimitEscape_t4 {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", - "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3) j1 join (select j4.id from (select TOP 5 * from UnitStatement_LimitEscape_t3) j4 join (select TOP 6 * from UnitStatement_LimitEscape_t4) j5 on j4.id = j5.id ) j2 on j1.id = j2.id", + "select j1.id from (select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + " {limit 5}) j4 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + " {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", + "select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + ") j3) j1 join (select j4.id from (select TOP 5 * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + ") j4 join (select TOP 6 * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + ") j5 on j4.id = j5.id ) j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -377,8 +419,12 @@ public void initAndVerifyQueries() throws Exception { // 11 // Test multiple parentheses/spaces in limit syntax, also test '[]' in columns - qry = new Query("select [col1], col2, [col3], col4 from [UnitStatement_LimitEscape_t1] {limit ( ( (2)))}", - "select TOP ( ( (2))) [col1], col2, [col3], col4 from [UnitStatement_LimitEscape_t1]", 2, // # of rows + qry = new Query( + "select [col1], col2, [col3], col4 from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit ( ( (2)))}", + "select TOP ( ( (2))) [col1], col2, [col3], col4 from " + + AbstractSQLGenerator.escapeIdentifier(table1), + 2, // # of rows 4, // # of columns new int[] {1, 2}, // id column values new int[][] {{1, 1}, {2, 2}}, // int column values @@ -390,8 +436,16 @@ public void initAndVerifyQueries() throws Exception { // 12 // Test complicated query with nested subquery having limit syntax qry = new Query( - "select j1.id from ( ((select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}))) j1 join (select j4.id from ((((select * from UnitStatement_LimitEscape_t3 {limit 5})))) j4 join (select * from UnitStatement_LimitEscape_t4 {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", - "select TOP 1 j1.id from ( ((select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3))) j1 join (select j4.id from ((((select TOP 5 * from UnitStatement_LimitEscape_t3)))) j4 join (select TOP 6 * from UnitStatement_LimitEscape_t4) j5 on j4.id = j5.id ) j2 on j1.id = j2.id", + "select j1.id from ( ((select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}))) j1 join (select j4.id from ((((select * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + " {limit 5})))) j4 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + " {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}", + "select TOP 1 j1.id from ( ((select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + ") j3))) j1 join (select j4.id from ((((select TOP 5 * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + ")))) j4 join (select TOP 6 * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + ") j5 on j4.id = j5.id ) j2 on j1.id = j2.id", 1, // # of rows 1, // # of columns new int[] {1}, // id column values @@ -401,8 +455,9 @@ public void initAndVerifyQueries() throws Exception { // 13 // Test prepared statements with limit syntax with multiple parentheses/spaces - qry = new PreparedQuery("select * from UnitStatement_LimitEscape_t1 {limit ( ( (?)))}", - "select TOP ( ( (?))) * from UnitStatement_LimitEscape_t1", 1, // # of rows + qry = new PreparedQuery( + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit ( ( (?)))}", + "select TOP ( ( (?))) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -411,10 +466,10 @@ public void initAndVerifyQueries() throws Exception { // 14 // Test prepared statements with limit syntax - qry = new PreparedQuery("select * from UnitStatement_LimitEscape_t1 {limit (?)}", - "select TOP (?) * from UnitStatement_LimitEscape_t1", 1, // # - // of - // rows + qry = new PreparedQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit (?)}", + "select TOP (?) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # + // of + // rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -423,10 +478,10 @@ public void initAndVerifyQueries() throws Exception { // 15 // Test prepared statements with limit syntax with multiple parentheses/spaces - qry = new PreparedQuery("select * from UnitStatement_LimitEscape_t1 {limit ?}", - "select TOP (?) * from UnitStatement_LimitEscape_t1", 1, // # - // of - // rows + qry = new PreparedQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit ?}", + "select TOP (?) * from " + AbstractSQLGenerator.escapeIdentifier(table1), 1, // # + // of + // rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -435,8 +490,12 @@ public void initAndVerifyQueries() throws Exception { // 16 // Test prepared statements with limit syntax with subqueries - qry = new PreparedQuery("select * from (select * from UnitStatement_LimitEscape_t1 {limit ?}) t1 {limit (?)}", - "select TOP (?) * from (select TOP (?) * from UnitStatement_LimitEscape_t1) t1", 1, // # of rows + qry = new PreparedQuery( + "select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit ?}) t1 {limit (?)}", + "select TOP (?) * from (select TOP (?) * from " + AbstractSQLGenerator.escapeIdentifier(table1) + + ") t1", + 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -445,8 +504,10 @@ public void initAndVerifyQueries() throws Exception { // 17 // Test callable statements as they are also translated by the driver - qry = new CallableQuery("EXEC UnitStatement_LimitEscape_p1 @col3Value = 'col3', @col4Value = 'col4'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'col3', @col4Value = 'col4'", 1, // # of rows + qry = new CallableQuery( + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col3Value = 'col3', @col4Value = 'col4'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col3Value = 'col3', @col4Value = 'col4'", + 1, // # of rows 5, // # of columns new int[] {1}, // id column values new int[][] {{1, 1}}, // int column values @@ -456,8 +517,10 @@ public void initAndVerifyQueries() throws Exception { // 18 // Test callable statements with limit syntax in string literals qry = new CallableQuery( - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row2 '' with '' quote', @col4Value = 'row2 with limit {limit 22} {limit ?}'", 1, // # // of // rows @@ -469,9 +532,10 @@ public void initAndVerifyQueries() throws Exception { // 19 // Test callable statements with subquery/limit syntax in string literals - qry = new CallableQuery( - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", + qry = new CallableQuery("EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'row3 with subquery (select * from t1)', @col4Value = 'row3 with subquery (select * from (select * from t1) {limit 4})'", 1, // # of rows 5, // # of columns new int[] {3}, // id column values @@ -483,9 +547,10 @@ public void initAndVerifyQueries() throws Exception { // 20 // Test callable statements with quotes/scalar functions/limit syntax in string literals - qry = new CallableQuery( - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", - "EXEC UnitStatement_LimitEscape_p1 @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", + qry = new CallableQuery("EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col3Value = 'select * from t1 {limit 4} ''quotes'' (braces)', @col4Value = 'ucase(scalar function)'", 1, // # of rows 5, // # of columns new int[] {4}, // id column values @@ -496,9 +561,13 @@ public void initAndVerifyQueries() throws Exception { // 21 // Test callable statement escape syntax with quotes/scalar functions/limit syntax in string literals qry = new CallableQuery( - "{call UnitStatement_LimitEscape_p1 ('select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)')}", - "EXEC UnitStatement_LimitEscape_p1 'select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)'", - 1, // # of rows + "{call " + AbstractSQLGenerator.escapeIdentifier(procName) + + " ('select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)')}", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " 'select * from t1 {limit 4} ''quotes'' (braces)', 'ucase(scalar function)'", + 1, // # + // of + // rows 5, // # of columns new int[] {4}, // id column values new int[][] {{4, 4}}, // int column value @@ -507,9 +576,10 @@ public void initAndVerifyQueries() throws Exception { // 22 // Test callable statement escape syntax with openrowquery/openrowset/quotes in string literals - qry = new CallableQuery( - "{call UnitStatement_LimitEscape_p1 ('openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')')}", - "EXEC UnitStatement_LimitEscape_p1 'openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')'", + qry = new CallableQuery("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + + " ('openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')')}", + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + + " 'openquery(''server'', ''query'')', 'openrowset(''server'',''connection string'',''query'')'", 1, // # // of // rows @@ -524,10 +594,13 @@ public void initAndVerifyQueries() throws Exception { // 23 // Test openquery syntax translation with limit syntax qry = new Query( - "select * from openquery('linked_server', 'select * from UnitStatement_LimitEscape_t1 {limit 2}') {limit 1}", - "select TOP 1 * from openquery('linked_server', 'select TOP 2 * from UnitStatement_LimitEscape_t1')", 1, // # - // of - // rows + "select * from openquery('linked_server', 'select * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 2}') {limit 1}", + "select TOP 1 * from openquery('linked_server', 'select TOP 2 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + "')", + 1, // # + // of + // rows 5, // # of columns new int[] {5}, // id column values new int[][] {{5, 5}}, // int column value @@ -537,8 +610,18 @@ public void initAndVerifyQueries() throws Exception { // 24 // Test openrowset syntax translation with a complicated query with subqueries and limit syntax qry = new Query( - "select * from openrowset('provider_name', 'provider_string', 'select j1.id from (select * from (select * from UnitStatement_LimitEscape_t1 {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from UnitStatement_LimitEscape_t3 {limit 5}) j4 join (select * from UnitStatement_LimitEscape_t4 {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}') {limit 1}", - "select TOP 1 * from openrowset('provider_name', 'provider_string', 'select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from UnitStatement_LimitEscape_t1) j3) j1 join (select j4.id from (select TOP 5 * from UnitStatement_LimitEscape_t3) j4 join (select TOP 6 * from UnitStatement_LimitEscape_t4) j5 on j4.id = j5.id ) j2 on j1.id = j2.id')", + "select * from openrowset('provider_name', 'provider_string', 'select j1.id from (select * from (select * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + " {limit 3}) j3 {limit 2}) j1 join (select j4.id from (select * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + " {limit 5}) j4 join (select * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + " {limit 6}) j5 on j4.id = j5.id ) j2 on j1.id = j2.id {limit 1}') {limit 1}", + "select TOP 1 * from openrowset('provider_name', 'provider_string', 'select TOP 1 j1.id from (select TOP 2 * from (select TOP 3 * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + + ") j3) j1 join (select j4.id from (select TOP 5 * from " + + AbstractSQLGenerator.escapeIdentifier(table3) + ") j4 join (select TOP 6 * from " + + AbstractSQLGenerator.escapeIdentifier(table4) + + ") j5 on j4.id = j5.id ) j2 on j1.id = j2.id')", 1, // # of rows 5, // # of columns new int[] {5}, // id column values @@ -547,8 +630,10 @@ public void initAndVerifyQueries() throws Exception { // 25 // Test offset syntax in string literals - qry = new Query("select * from UnitStatement_LimitEscape_t1 where col3 = '{limit 1 offset 2}'", - "select * from UnitStatement_LimitEscape_t1 where col3 = '{limit 1 offset 2}'", 0, // # of rows + qry = new Query( + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = '{limit 1 offset 2}'", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = '{limit 1 offset 2}'", + 0, // # of rows 5, // # of columns null, // id column values null, // int column values @@ -560,10 +645,13 @@ public void initAndVerifyQueries() throws Exception { // Only test the syntax translation. // Test batch query. qry = new Query( - "select * from UnitStatement_LimitEscape_t1 {limit 1}; select * from UnitStatement_LimitEscape_t1 {limit 4}", - "select TOP 1 * from UnitStatement_LimitEscape_t1; select TOP 4 * from UnitStatement_LimitEscape_t1", 0, // # - // of - // rows + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}; select * from " + + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 4}", + "select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + "; select TOP 4 * from " + + AbstractSQLGenerator.escapeIdentifier(table1), + 0, // # + // of + // rows 5, // # of columns null, // id column values null, // int column values @@ -571,8 +659,9 @@ public void initAndVerifyQueries() throws Exception { // 27 // Execute query, and verify exception for unclosed quotation marks. - qry = new Query("select * from UnitStatement_LimitEscape_t1 where col3 = 'abcd", - "select * from UnitStatement_LimitEscape_t1 where col3 = 'abcd", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = 'abcd", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " where col3 = 'abcd", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -583,20 +672,20 @@ public void initAndVerifyQueries() throws Exception { // 28 // Execute query, and verify exception for unclosed subquery. - qry = new Query("select * from (select * from UnitStatement_LimitEscape_t1 {limit 1}", - "select * from (select TOP 1 * from UnitStatement_LimitEscape_t1", 0, // # of rows + qry = new Query("select * from (select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}", + "select * from (select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1), 0, // # of rows 0, // # of columns null, // id column values null, // int column values null); // string column values // Verified that SQL Server throws an exception with this message for similar errors. - qry.setExceptionMsg("Incorrect syntax near 'UnitStatement_LimitEscape_t1'."); + qry.setExceptionMsg("Incorrect syntax near '" + table1 + "'."); qry.execute(conn); // 29 // Execute query, and verify exception for syntax error in select. - qry = new Query("selectsel * from from UnitStatement_LimitEscape_t1 {limit 1}", - "selectsel * from from UnitStatement_LimitEscape_t1 {limit 1}", 0, // # of rows + qry = new Query("selectsel * from from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}", + "selectsel * from from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -608,8 +697,8 @@ public void initAndVerifyQueries() throws Exception { // 29 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit1}", - "select * from UnitStatement_LimitEscape_t1 {limit1}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -621,9 +710,9 @@ public void initAndVerifyQueries() throws Exception { // 30 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit(1}", - "select * from UnitStatement_LimitEscape_t1 {limit(1}", 0, // # of - // rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit(1}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit(1}", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -635,8 +724,9 @@ public void initAndVerifyQueries() throws Exception { // 31 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit 1 offset10}", - "select * from UnitStatement_LimitEscape_t1 {limit 1 offset10}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1 offset10}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1 offset10}", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -648,8 +738,9 @@ public void initAndVerifyQueries() throws Exception { // 32 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit1 offset 10}", - "select * from UnitStatement_LimitEscape_t1 {limit1 offset 10}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset 10}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset 10}", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -661,8 +752,8 @@ public void initAndVerifyQueries() throws Exception { // 33 // Execute query, and verify exception for limit syntax error. The translator should leave the query unchanged // as limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit1 offset10}", - "select * from UnitStatement_LimitEscape_t1 {limit1 offset10}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset10}", + "select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit1 offset10}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -674,8 +765,9 @@ public void initAndVerifyQueries() throws Exception { // 34 // Execute query, and verify exception for syntax error. The translator should leave the query unchanged as // limit syntax is not correct. - qry = new Query("insert into UnitStatement_LimitEscape_t1(col3) values({limit 1})", - "insert into UnitStatement_LimitEscape_t1(col3) values({limit 1})", 0, // # of rows + qry = new Query("insert into " + AbstractSQLGenerator.escapeIdentifier(table1) + "(col3) values({limit 1})", + "insert into " + AbstractSQLGenerator.escapeIdentifier(table1) + "(col3) values({limit 1})", 0, // # of + // rows 0, // # of columns null, // id column values null, // int column values @@ -687,10 +779,10 @@ public void initAndVerifyQueries() throws Exception { // 35 // Execute query, and verify exception for syntax error. The translator should leave the query unchanged as // limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit {limit 5}}", - "select TOP 5 * from UnitStatement_LimitEscape_t1 {limit}", 0, // # - // of - // rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit {limit 5}}", + "select TOP 5 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit}", 0, // # + // of + // rows 0, // # of columns null, // id column values null, // int column values @@ -702,8 +794,8 @@ public void initAndVerifyQueries() throws Exception { // 36 // Execute query, and verify exception for syntax error. The translator should leave the query unchanged as // limit syntax is not correct. - qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit 1} {limit 2}", - "select TOP 1 * from UnitStatement_LimitEscape_t1 {limit 2}", 0, // # of rows + qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 1} {limit 2}", + "select TOP 1 * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit 2}", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -723,12 +815,22 @@ public void initAndVerifyQueries() throws Exception { @Test @DisplayName("verifyOffsetException") public void verifyOffsetException() throws Exception { - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit 2 offset 1}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit 2232 offset 1232}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit (2) offset (1)}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit (265) offset (1972)}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit ? offset ?}"); - offsetQuery.addElement("select * from UnitStatement_LimitEscape_t1 {limit (?) offset (?)}"); + offsetQuery.addElement("select * from " + + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + " {limit 2 offset 1}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit 2232 offset 1232}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit (2) offset (1)}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit (265) offset (1972)}"); + offsetQuery.addElement("select * from " + + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + " {limit ? offset ?}"); + offsetQuery.addElement( + "select * from " + AbstractSQLGenerator.escapeIdentifier(TestUtils.escapeSingleQuotes(table1)) + + " {limit (?) offset (?)}"); int i; for (i = 0; i < offsetQuery.size(); ++i) { @@ -749,7 +851,8 @@ public void verifyOffsetException() throws Exception { // Test the parsing error with unmatched braces in limit clause try { // Do not execute query. Exception will be thrown when verifying translation. - Query qry = new Query("select * from UnitStatement_LimitEscape_t1 {limit (2))}", "", 0, // # of rows + Query qry = new Query("select * from " + AbstractSQLGenerator.escapeIdentifier(table1) + " {limit (2))}", + "", 0, // # of rows 0, // # of columns null, // id column values null, // int column values @@ -783,10 +886,11 @@ public static void beforeAll() { public static void afterAll() throws Exception { try (Statement stmt = conn.createStatement()) { - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); - TestUtils.dropTableIfExists("UnitStatement_LimitEscape_t4", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table3), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table4), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (Exception ex) { fail(ex.toString()); } finally { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java index 5e5c0ffb13..2d00d9cdc9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java @@ -18,8 +18,10 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; @@ -30,17 +32,28 @@ */ @RunWith(JUnitPlatform.class) public class MergeTest extends AbstractTest { - private static final String setupTables = "IF OBJECT_ID (N'dbo.CricketTeams', N'U') IS NOT NULL DROP TABLE dbo.CricketTeams;" - + " CREATE TABLE dbo.CricketTeams ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" - + " INSERT INTO dbo.CricketTeams VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia'), (6, 'HongKong', 'Asia')," + static String cricketTeams = RandomUtil.getIdentifier("CricketTeams"); + static String cricketTeamsUpdated = RandomUtil.getIdentifier("cricketTeamsUpdated"); + + private static final String setupTables = "IF OBJECT_ID (N'" + TestUtils.escapeSingleQuotes(cricketTeams) + + "', N'U') IS NOT NULL DROP TABLE " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + ";" + + " CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + + " ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" + + " INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + + " VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia'), (6, 'HongKong', 'Asia')," + " (7, 'U.A.E', 'Asia'), (8, 'England', 'Europe'), (9, 'South Africa', 'Africa'), (10, 'West Indies', 'North America');" - + " SELECT * FROM CricketTeams IF OBJECT_ID (N'dbo.CricketTeams_UpdatedList', N'U') IS NOT NULL DROP TABLE dbo.CricketTeams_UpdatedList;" - + " CREATE TABLE dbo.CricketTeams_UpdatedList ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" - + "INSERT INTO dbo.CricketTeams_UpdatedList VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia')," + + " SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + " IF OBJECT_ID (N'" + + TestUtils.escapeSingleQuotes(cricketTeams) + "_UpdatedList', N'U') IS NOT NULL DROP TABLE " + + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + ";" + " CREATE TABLE " + + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + + " ( CricketTeamID tinyint NOT NULL PRIMARY KEY, CricketTeamCountry nvarchar(30), CricketTeamContinent nvarchar(50))" + + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + + " VALUES (1, 'Australia', 'Australia'), (2, 'India', 'Asia'), (3, 'Pakistan', 'Asia'), (4, 'Srilanka', 'Asia'), (5, 'Bangaladesh', 'Asia')," + " (6, 'Thailand', 'Asia'), (8, 'England', 'Europe'), (9, 'South Africa', 'Africa'), (10, 'West Indies', 'North America'), (11, 'Zimbabwe', 'Africa');"; - private static final String mergeCmd2 = "MERGE dbo.CricketTeams AS TARGET " - + "USING dbo.CricketTeams_UpdatedList AS SOURCE " + "ON (TARGET.CricketTeamID = SOURCE.CricketTeamID) " + private static final String mergeCmd2 = "MERGE " + AbstractSQLGenerator.escapeIdentifier(cricketTeams) + + " AS TARGET " + "USING " + AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated) + " AS SOURCE " + + "ON (TARGET.CricketTeamID = SOURCE.CricketTeamID) " + "WHEN MATCHED AND TARGET.CricketTeamContinent <> SOURCE.CricketTeamContinent OR " + "TARGET.CricketTeamCountry <> SOURCE.CricketTeamCountry " + "THEN UPDATE SET TARGET.CricketTeamContinent = SOURCE.CricketTeamContinent ," @@ -81,7 +94,8 @@ public static void afterAll() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists("dbo.CricketTeams", stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(cricketTeams), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(cricketTeamsUpdated), stmt); } catch (Exception ex) { fail(ex.toString()); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java index b50b36278d..c5a654cf26 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java @@ -19,8 +19,10 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @@ -30,8 +32,8 @@ */ @RunWith(JUnitPlatform.class) public class NamedParamMultiPartTest extends AbstractTest { - private static final String dataPut = "eminem"; - String procedureName = "mystoredproc"; + private static final String dataPut = RandomUtil.getIdentifier("dataPut"); + static String procedureName; /** * setup @@ -40,11 +42,13 @@ public class NamedParamMultiPartTest extends AbstractTest { */ @BeforeAll public static void beforeAll() throws SQLException { + procedureName = RandomUtil.getIdentifier("mystoredproc"); + try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement()) { - TestUtils.dropProcedureIfExists("mystoredproc", statement); - statement.executeUpdate( - "CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), statement); + statement.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procedureName) + + " (@p_out varchar(255) OUTPUT) AS set @p_out = '" + TestUtils.escapeSingleQuotes(dataPut) + "'"); } } @@ -55,8 +59,8 @@ public static void beforeAll() throws SQLException { */ @Test public void update1() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); String data = cs.getString("p_out"); @@ -71,8 +75,8 @@ public void update1() throws Exception { */ @Test public void update2() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -88,7 +92,7 @@ public void update2() throws Exception { @Test public void update3() throws Exception { String catalog = connection.getCatalog(); - String storedproc = "[" + catalog + "]" + ".[dbo].[mystoredproc]"; + String storedproc = "[" + catalog + "]" + ".[dbo]." + AbstractSQLGenerator.escapeIdentifier(procedureName); try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); @@ -105,8 +109,8 @@ public void update3() throws Exception { */ @Test public void update4() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -121,8 +125,8 @@ public void update4() throws Exception { */ @Test public void update5() throws Exception { - try (Connection connection = DriverManager.getConnection(connectionString); - CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection + .prepareCall("{ CALL " + AbstractSQLGenerator.escapeIdentifier(procedureName) + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); cs.executeUpdate(); Object data = cs.getObject("p_out"); @@ -137,7 +141,7 @@ public void update5() throws Exception { @Test public void update6() throws Exception { String catalog = connection.getCatalog(); - String storedproc = catalog + ".dbo." + procedureName; + String storedproc = catalog + ".dbo." + AbstractSQLGenerator.escapeIdentifier(procedureName); try (Connection connection = DriverManager.getConnection(connectionString); CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { cs.registerOutParameter("p_out", Types.VARCHAR); @@ -156,7 +160,7 @@ public void update6() throws Exception { public static void afterAll() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - TestUtils.dropProcedureIfExists("mystoredproc", stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procedureName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java index 32352d8cf0..86e150397d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java @@ -46,22 +46,16 @@ public class PQImpsTest extends AbstractTest { private static ResultSet versionRS = null; private static int version = -1; - private static String nameTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("names_DB")); - private static String phoneNumberTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("phoneNumbers_DB")); - private static String mergeNameDesTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("mergeNameDesTable_DB")); - private static String numericTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("numericTable_DB")); - private static String charTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("charTable_DB")); - private static String charTable2 = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("charTable2_DB")); - private static String binaryTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("binaryTable_DB")); - private static String dateAndTimeTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("dateAndTimeTable_DB")); - private static String multipleTypesTable = AbstractSQLGenerator - .escapeIdentifier(RandomUtil.getIdentifier("multipleTypesTable_DB")); - private static String spaceTable = AbstractSQLGenerator.escapeIdentifier(RandomUtil.getIdentifier("spaceTable_DB")); + private static String nameTable = RandomUtil.getIdentifier("names_DB"); + private static String phoneNumberTable = RandomUtil.getIdentifier("phoneNumbers_DB"); + private static String mergeNameDesTable = RandomUtil.getIdentifier("mergeNameDesTable_DB"); + private static String numericTable = RandomUtil.getIdentifier("numericTable_DB"); + private static String charTable = RandomUtil.getIdentifier("charTable_DB"); + private static String charTable2 = RandomUtil.getIdentifier("charTable2_DB"); + private static String binaryTable = RandomUtil.getIdentifier("binaryTable_DB"); + private static String dateAndTimeTable = RandomUtil.getIdentifier("dateAndTimeTable_DB"); + private static String multipleTypesTable = RandomUtil.getIdentifier("multipleTypesTable_DB"); + private static String spaceTable = RandomUtil.getIdentifier("spaceTable_DB"); /** * Setup @@ -330,9 +324,9 @@ private static void compareParameterMetaData(ParameterMetaData pmd, int index, S } private static void populateNumericTable() throws SQLException { - stmt.execute("insert into " + numericTable + " values (" + "1.123," + "1.123," + "1.2345," + "1.2345," - + "1.543," + "1.543," + "5.1234," + "104935," + "34323," + "123," + "5," + "1.45," + "1.3," - + "0.123456789," + "0.1234567890123456789012345678901234567" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values (" + "1.123," + + "1.123," + "1.2345," + "1.2345," + "1.543," + "1.543," + "5.1234," + "104935," + "34323," + "123," + + "5," + "1.45," + "1.3," + "0.123456789," + "0.1234567890123456789012345678901234567" + ")"); } private static void testBeforeExcute() throws SQLException { @@ -340,9 +334,10 @@ private static void testBeforeExcute() throws SQLException { pstmt.close(); } - String sql = "select * from " + numericTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? and " - + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + "c14 = ? and " + "c15 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + + "c8 = ? and " + "c9 = ? and " + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + + "c14 = ? and " + "c15 = ? "; pstmt = connection.prepareStatement(sql); @@ -354,9 +349,10 @@ private static void testBeforeExcute() throws SQLException { } private static void selectNumeric() throws SQLException { - String sql = "select * from " + numericTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? and " - + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + "c14 = ? and " + "c15 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + + "c8 = ? and " + "c9 = ? and " + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + + "c14 = ? and " + "c15 = ? "; pstmt = connection.prepareStatement(sql); @@ -369,8 +365,8 @@ private static void selectNumeric() throws SQLException { private static void insertNumeric() throws SQLException { - String sql = "insert into " + numericTable + " values( " + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," - + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " values( " + "?," + "?," + + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ")"; pstmt = connection.prepareStatement(sql); @@ -383,9 +379,9 @@ private static void insertNumeric() throws SQLException { private static void updateNumeric() throws SQLException { - String sql = "update " + numericTable + " set " + "c1 = ?," + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," - + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?," + "c10 = ?," + "c11 = ?," + "c12 = ?," + "c13 = ?," - + "c14 = ?," + "c15 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " set " + "c1 = ?," + "c2 = ?," + + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?," + "c10 = ?," + + "c11 = ?," + "c12 = ?," + "c13 = ?," + "c14 = ?," + "c15 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -398,9 +394,10 @@ private static void updateNumeric() throws SQLException { private static void deleteNumeric() throws SQLException { - String sql = "delete from " + numericTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? and " - + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + "c14 = ? and " + "c15 = ?" + ";"; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + + "c8 = ? and " + "c9 = ? and " + "c10 = ? and " + "c11 = ? and " + "c12 = ? and " + "c13 = ? and " + + "c14 = ? and " + "c15 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -413,38 +410,41 @@ private static void deleteNumeric() throws SQLException { private static void createNumericTable() throws SQLException { - stmt.execute("Create table " + numericTable + " (" + "c1 decimal not null," + "c2 decimal(10,5) not null," - + "c3 numeric not null," + "c4 numeric(8,4) not null," + "c5 float not null," + "c6 float(10) not null," - + "c7 real not null," + "c8 int not null," + "c9 bigint not null," + "c10 smallint not null," - + "c11 tinyint not null," + "c12 money not null," + "c13 smallmoney not null," - + "c14 decimal(10,9) not null," + "c15 decimal(38,37) not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(numericTable) + " (" + + "c1 decimal not null," + "c2 decimal(10,5) not null," + "c3 numeric not null," + + "c4 numeric(8,4) not null," + "c5 float not null," + "c6 float(10) not null," + "c7 real not null," + + "c8 int not null," + "c9 bigint not null," + "c10 smallint not null," + "c11 tinyint not null," + + "c12 money not null," + "c13 smallmoney not null," + "c14 decimal(10,9) not null," + + "c15 decimal(38,37) not null" + ")"); } private static void createCharTable() throws SQLException { - stmt.execute("Create table " + charTable + " (" + "c1 char(50) not null," + "c2 varchar(20) not null," - + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," + "c5 text not null," + "c6 ntext not null" - + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (" + "c1 char(50) not null," + + "c2 varchar(20) not null," + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," + + "c5 text not null," + "c6 ntext not null" + ")"); } private static void createSpaceTable() throws SQLException { - stmt.execute("Create table " + spaceTable + " (" + "[c1*/someString withspace] char(50) not null," - + "c2 varchar(20) not null," + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," - + "c5 text not null," + "c6 ntext not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(spaceTable) + " (" + + "[c1*/someString withspace] char(50) not null," + "c2 varchar(20) not null," + + "c3 nchar(30) not null," + "c4 nvarchar(60) not null," + "c5 text not null," + "c6 ntext not null" + + ")"); } private static void createChar2Table() throws SQLException { - stmt.execute("Create table " + charTable2 + " (" + "table2c1 char(50) not null)"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(charTable2) + " (" + + "table2c1 char(50) not null)"); } private static void populateCharTable() throws SQLException { - stmt.execute("insert into " + charTable + " values (" + "'Hello'," + "'Hello'," + "N'Hello'," + "N'Hello'," - + "'Hello'," + "N'Hello'" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values (" + "'Hello'," + + "'Hello'," + "N'Hello'," + "N'Hello'," + "'Hello'," + "N'Hello'" + ")"); } private static void selectChar() throws SQLException { - String sql = "select * from " + charTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? "; pstmt = connection.prepareStatement(sql); @@ -457,7 +457,8 @@ private static void selectChar() throws SQLException { private static void insertChar() throws SQLException { - String sql = "insert into " + charTable + " values( " + "?," + "?," + "?," + "?," + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " values( " + "?," + "?," + + "?," + "?," + "?," + "?" + ")"; pstmt = connection.prepareStatement(sql); @@ -470,8 +471,8 @@ private static void insertChar() throws SQLException { private static void updateChar() throws SQLException { - String sql = "update " + charTable + " set " + "c1 = ?," + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," - + "c6 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(charTable) + " set " + "c1 = ?," + "c2 = ?," + + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -484,7 +485,8 @@ private static void updateChar() throws SQLException { private static void deleteChar() throws SQLException { - String sql = "delete from " + charTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " + "c4 = ? "; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where " + "c1 = ? and " + + "c2 = ? and " + "c3 = ? and " + "c4 = ? "; pstmt = connection.prepareStatement(sql); @@ -497,18 +499,19 @@ private static void deleteChar() throws SQLException { private static void createBinaryTable() throws SQLException { - stmt.execute( - "Create table " + binaryTable + " (" + "c1 binary(100) not null," + "c2 varbinary(200) not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " (" + + "c1 binary(100) not null," + "c2 varbinary(200) not null" + ")"); } private static void populateBinaryTable() throws SQLException { - stmt.execute("insert into " + binaryTable + " values (" + "convert(binary(50), 'Simba tech', 0), " - + "convert(varbinary(50), 'Simba tech', 0)" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values (" + + "convert(binary(50), 'Simba tech', 0), " + "convert(varbinary(50), 'Simba tech', 0)" + ")"); } private static void selectBinary() throws SQLException { - String sql = "select * from " + binaryTable + " where " + "c1 = ? and " + "c2 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " where " + "c1 = ? and " + + "c2 = ? "; pstmt = connection.prepareStatement(sql); @@ -521,7 +524,8 @@ private static void selectBinary() throws SQLException { private static void insertBinary() throws SQLException { - String sql = "insert into " + binaryTable + " values( " + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " values( " + "?," + "?" + + ")"; pstmt = connection.prepareStatement(sql); @@ -535,7 +539,8 @@ private static void insertBinary() throws SQLException { private static void updateBinary() throws SQLException { - String sql = "update " + binaryTable + " set " + "c1 = ?," + "c2 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " set " + "c1 = ?," + "c2 = ?" + + ";"; pstmt = connection.prepareStatement(sql); @@ -549,7 +554,8 @@ private static void updateBinary() throws SQLException { private static void deleteBinary() throws SQLException { - String sql = "delete from " + binaryTable + " where " + "c1 = ? and " + "c2 = ?" + ";"; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(binaryTable) + " where " + "c1 = ? and " + + "c2 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -562,22 +568,23 @@ private static void deleteBinary() throws SQLException { private static void createDateAndTimeTable() throws SQLException { - stmt.execute("Create table " + dateAndTimeTable + " (" + "c1 date not null," + "c2 datetime not null," - + "c3 datetime2 not null," + "c4 datetime2(5) not null," + "c5 datetimeoffset not null," - + "c6 datetimeoffset(5) not null," + "c7 smalldatetime not null," + "c8 time not null," - + "c9 time(5) not null" + ")"); + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " (" + + "c1 date not null," + "c2 datetime not null," + "c3 datetime2 not null," + "c4 datetime2(5) not null," + + "c5 datetimeoffset not null," + "c6 datetimeoffset(5) not null," + "c7 smalldatetime not null," + + "c8 time not null," + "c9 time(5) not null" + ")"); } private static void populateDateAndTimeTable() throws SQLException { - stmt.execute("insert into " + dateAndTimeTable + " values (" + "'1991-10-23'," + "'1991-10-23 06:20:50'," - + "'1991-10-23 07:20:50.123'," + "'1991-10-23 07:20:50.123'," + "'1991-10-23 08:20:50.123'," - + "'1991-10-23 08:20:50.123'," + "'1991-10-23 09:20:50'," + "'10:20:50'," + "'10:20:50'" + ")"); + stmt.execute("insert into " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " values (" + + "'1991-10-23'," + "'1991-10-23 06:20:50'," + "'1991-10-23 07:20:50.123'," + + "'1991-10-23 07:20:50.123'," + "'1991-10-23 08:20:50.123'," + "'1991-10-23 08:20:50.123'," + + "'1991-10-23 09:20:50'," + "'10:20:50'," + "'10:20:50'" + ")"); } private static void insertDateAndTime() throws SQLException { - String sql = "insert into " + dateAndTimeTable + " values( " + "?," + "?," + "?," + "?," + "?," + "?," + "?," - + "?," + "?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " values( " + "?," + + "?," + "?," + "?," + "?," + "?," + "?," + "?," + "?" + ")"; pstmt = connection.prepareStatement(sql); @@ -590,8 +597,8 @@ private static void insertDateAndTime() throws SQLException { private static void updateDateAndTime() throws SQLException { - String sql = "update " + dateAndTimeTable + " set " + "c1 = ?," + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," - + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?" + ";"; + String sql = "update " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " set " + "c1 = ?," + + "c2 = ?," + "c3 = ?," + "c4 = ?," + "c5 = ?," + "c6 = ?," + "c7 = ?," + "c8 = ?," + "c9 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -604,8 +611,9 @@ private static void updateDateAndTime() throws SQLException { private static void deleteDateAndTime() throws SQLException { - String sql = "delete from " + dateAndTimeTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ?" + ";"; + String sql = "delete from " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " where " + + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + + "c7 = ? and " + "c8 = ? and " + "c9 = ?" + ";"; pstmt = connection.prepareStatement(sql); @@ -617,8 +625,9 @@ private static void deleteDateAndTime() throws SQLException { } private static void selectDateAndTime() throws SQLException { - String sql = "select * from " + dateAndTimeTable + " where " + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " - + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + "c7 = ? and " + "c8 = ? and " + "c9 = ? "; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable) + " where " + + "c1 = ? and " + "c2 = ? and " + "c3 = ? and " + "c4 = ? and " + "c5 = ? and " + "c6 = ? and " + + "c7 = ? and " + "c8 = ? and " + "c9 = ? "; pstmt = connection.prepareStatement(sql); @@ -631,15 +640,15 @@ private static void selectDateAndTime() throws SQLException { private static void createTablesForCompexQueries() throws SQLException { stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(nameTable) + "','U') is not null" - + " drop table " + nameTable); + + " drop table " + AbstractSQLGenerator.escapeIdentifier(nameTable)); stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(phoneNumberTable) + "','U') is not null" - + " drop table " + phoneNumberTable); + + " drop table " + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable)); stmt.executeUpdate("if object_id('" + TestUtils.escapeSingleQuotes(mergeNameDesTable) + "','U') is not null" - + " drop table " + mergeNameDesTable); + + " drop table " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable)); - String sql = "create table " + nameTable + " (" + String sql = "create table " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " (" // + "ID int NOT NULL," + "PlainID int not null," + "ID smallint NOT NULL," + "FirstName varchar(50) NOT NULL," + "LastName nchar(60) NOT NULL" + ");"; @@ -650,8 +659,8 @@ private static void createTablesForCompexQueries() throws SQLException { fail(e.toString()); } - sql = "create table " + phoneNumberTable + " (" + "PlainID smallint not null," + "ID int NOT NULL," - + "PhoneNumber bigint NOT NULL" + ");"; + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + " (" + + "PlainID smallint not null," + "ID int NOT NULL," + "PhoneNumber bigint NOT NULL" + ");"; try { stmt.execute(sql); @@ -659,7 +668,7 @@ private static void createTablesForCompexQueries() throws SQLException { fail(e.toString()); } - sql = "create table " + mergeNameDesTable + " (" + sql = "create table " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable) + " (" // + "ID int NOT NULL," + "PlainID smallint not null," + "ID int NULL," + "FirstName char(30) NULL," + "LastName varchar(50) NULL" + ");"; @@ -672,7 +681,8 @@ private static void createTablesForCompexQueries() throws SQLException { } private static void populateTablesForCompexQueries() throws SQLException { - String sql = "insert into " + nameTable + " values " + "(?,?,?,?)," + "(?,?,?,?)," + "(?,?,?,?)" + ""; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " values " + "(?,?,?,?)," + + "(?,?,?,?)," + "(?,?,?,?)" + ""; pstmt = connection.prepareStatement(sql); int id = 1; for (int i = 0; i < 5; i++) { @@ -697,7 +707,8 @@ private static void populateTablesForCompexQueries() throws SQLException { } pstmt.close(); - sql = "insert into " + phoneNumberTable + " values " + "(?,?,?)," + "(?,?,?)," + "(?,?,?)" + ""; + sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + " values " + "(?,?,?)," + + "(?,?,?)," + "(?,?,?)" + ""; pstmt = connection.prepareStatement(sql); id = 1; for (int i = 0; i < 5; i++) { @@ -719,7 +730,8 @@ private static void populateTablesForCompexQueries() throws SQLException { } pstmt.close(); - sql = "insert into " + mergeNameDesTable + " (PlainID) values " + "(?)," + "(?)," + "(?)" + ""; + sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable) + " (PlainID) values " + "(?)," + + "(?)," + "(?)" + ""; pstmt = connection.prepareStatement(sql); id = 1; for (int i = 0; i < 5; i++) { @@ -745,8 +757,10 @@ private static void populateTablesForCompexQueries() throws SQLException { @DisplayName("SubQuery") public void testSubquery() throws SQLException { if (version >= SQL_SERVER_2012_VERSION) { - String sql = "SELECT FirstName,LastName" + " FROM " + nameTable + " WHERE ID IN " + " (SELECT ID" + " FROM " - + phoneNumberTable + " WHERE PhoneNumber = ? and ID = ? and PlainID = ?" + ")"; + String sql = "SELECT FirstName,LastName" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + + " WHERE ID IN " + " (SELECT ID" + " FROM " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + + " WHERE PhoneNumber = ? and ID = ? and PlainID = ?" + ")"; pstmt = connection.prepareStatement(sql); @@ -777,8 +791,14 @@ public void testJoin() throws SQLException { String sql = String.format( "select %s.FirstName, %s.LastName, %s.PhoneNumber" + " from %s join %s on %s.PlainID = %s.PlainID" + " where %s.ID = ? and %s.PlainID = ?", - nameTable, nameTable, phoneNumberTable, nameTable, phoneNumberTable, nameTable, phoneNumberTable, - phoneNumberTable, phoneNumberTable); + AbstractSQLGenerator.escapeIdentifier(nameTable), AbstractSQLGenerator.escapeIdentifier(nameTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(nameTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(nameTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable)); pstmt = connection.prepareStatement(sql); @@ -805,8 +825,9 @@ public void testJoin() throws SQLException { @DisplayName("Merge Queries") public void testMerge() throws SQLException { if (version >= SQL_SERVER_2012_VERSION) { - String sql = "merge " + mergeNameDesTable + " as T" + " using " + nameTable + " as S" - + " on T.PlainID=S.PlainID" + " when matched" + " then update set T.firstName = ?, T.lastName = ?;"; + String sql = "merge " + AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable) + " as T" + " using " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + " as S" + " on T.PlainID=S.PlainID" + + " when matched" + " then update set T.firstName = ?, T.lastName = ?;"; pstmt = connection.prepareStatement(sql); @@ -830,11 +851,11 @@ public void testMerge() throws SQLException { private static void createMultipleTypesTable() throws SQLException { - stmt.execute("Create table " + multipleTypesTable + " (" + "c1n decimal not null," - + "c2n decimal(10,5) not null," + "c3n numeric not null," + "c4n numeric(8,4) not null," - + "c5n float not null," + "c6n float(10) not null," + "c7n real not null," + "c8n int not null," - + "c9n bigint not null," + "c10n smallint not null," + "c11n tinyint not null," + "c12n money not null," - + "c13n smallmoney not null," + stmt.execute("Create table " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable) + " (" + + "c1n decimal not null," + "c2n decimal(10,5) not null," + "c3n numeric not null," + + "c4n numeric(8,4) not null," + "c5n float not null," + "c6n float(10) not null," + + "c7n real not null," + "c8n int not null," + "c9n bigint not null," + "c10n smallint not null," + + "c11n tinyint not null," + "c12n money not null," + "c13n smallmoney not null," + "c1c char(50) not null," + "c2c varchar(20) not null," + "c3c nchar(30) not null," + "c4c nvarchar(60) not null," + "c5c text not null," + "c6c ntext not null," @@ -848,8 +869,8 @@ private static void createMultipleTypesTable() throws SQLException { private static void testInsertMultipleTypes() throws SQLException { - String sql = "insert into " + multipleTypesTable + " values( " + "?,?,?,?,?,?,?,?,?,?,?,?,?," + "?,?,?,?,?,?," - + "?,?," + "?,?,?,?,?,?,?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable) + " values( " + + "?,?,?,?,?,?,?,?,?,?,?,?,?," + "?,?,?,?,?,?," + "?,?," + "?,?,?,?,?,?,?,?,?" + ")"; pstmt = connection.prepareStatement(sql); @@ -919,7 +940,7 @@ private static void testInsertMultipleTypes() throws SQLException { @Test @DisplayName("testNoParameter") public void testNoParameter() throws SQLException { - String sql = "select * from " + multipleTypesTable; + String sql = "select * from " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable); pstmt = connection.prepareStatement(sql); @@ -936,8 +957,9 @@ public void testNoParameter() throws SQLException { private static void testMixedWithHardcodedValues() throws SQLException { - String sql = "insert into " + multipleTypesTable + " values( " + "1,?,?,1,?,?,?,1,?,?,?,1,1," - + "?,'simba tech','simba tech',?,?,?," + "?,?," + "?,'1991-10-23',?,?,?,'1991-10-23',?,?,?" + ")"; + String sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(multipleTypesTable) + " values( " + + "1,?,?,1,?,?,?,1,?,?,?,1,1," + "?,'simba tech','simba tech',?,?,?," + "?,?," + + "?,'1991-10-23',?,?,?,'1991-10-23',?,?,?" + ")"; pstmt = connection.prepareStatement(sql); @@ -1000,7 +1022,7 @@ private static void testMixedWithHardcodedValues() throws SQLException { @Test @DisplayName("Test OrderBy") public void testOrderBy() throws SQLException { - String sql = "SELECT FirstName,LastName" + " FROM " + nameTable + String sql = "SELECT FirstName,LastName" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? " + " ORDER BY ID ASC"; pstmt = connection.prepareStatement(sql); @@ -1029,7 +1051,7 @@ public void testOrderBy() throws SQLException { @Test @DisplayName("Test GroupBy") private void testGroupBy() throws SQLException { - String sql = "SELECT FirstName,COUNT(LastName)" + " FROM " + nameTable + String sql = "SELECT FirstName,COUNT(LastName)" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? " + " group by Firstname"; pstmt = connection.prepareStatement(sql); @@ -1057,7 +1079,7 @@ private void testGroupBy() throws SQLException { */ @Test public void testLower() throws SQLException { - String sql = "SELECT FirstName,LOWER(LastName)" + " FROM " + nameTable + String sql = "SELECT FirstName,LOWER(LastName)" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? "; pstmt = connection.prepareStatement(sql); @@ -1086,7 +1108,7 @@ public void testLower() throws SQLException { */ @Test public void testPower() throws SQLException { - String sql = "SELECT POWER(ID,2)" + " FROM " + nameTable + String sql = "SELECT POWER(ID,2)" + " FROM " + AbstractSQLGenerator.escapeIdentifier(nameTable) + " WHERE FirstName = ? and LastName = ? and PlainID = ? and ID = ? "; pstmt = connection.prepareStatement(sql); @@ -1117,10 +1139,16 @@ public void testPower() throws SQLException { public void testAllInOneQuery() throws SQLException { if (version >= SQL_SERVER_2012_VERSION) { - String sql = "select lower(FirstName), count(lastName) from " + nameTable + "where ID = ? and FirstName in" - + "(" + " select " + nameTable + ".FirstName from " + nameTable + " join " + phoneNumberTable - + " on " + nameTable + ".ID = " + phoneNumberTable + ".ID" + " where " + nameTable + ".ID = ? and " - + phoneNumberTable + ".ID = ?" + ")" + " group by FirstName " + " order by FirstName ASC"; + String sql = "select lower(FirstName), count(lastName) from " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + "where ID = ? and FirstName in" + "(" + + " select " + AbstractSQLGenerator.escapeIdentifier(nameTable) + ".FirstName from " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + " join " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + " on " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + ".ID = " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + ".ID" + " where " + + AbstractSQLGenerator.escapeIdentifier(nameTable) + ".ID = ? and " + + AbstractSQLGenerator.escapeIdentifier(phoneNumberTable) + ".ID = ?" + ")" + " group by FirstName " + + " order by FirstName ASC"; pstmt = connection.prepareStatement(sql); @@ -1147,7 +1175,8 @@ public void testAllInOneQuery() throws SQLException { */ @Test public void testQueryWithMultipleLineComments1() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/select top 100 c1 from " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/select top 100 c1 from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1167,7 +1196,7 @@ public void testQueryWithMultipleLineComments1() throws SQLException { public void testQueryWithMultipleLineComments2() throws SQLException { pstmt = connection .prepareStatement("/*/*te\nst*/ te/*test*/st /*te\nst*/*//*te/*test*/st*/select top 100 c1 from " - + charTable + " where c1 = ?"); + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1185,7 +1214,8 @@ public void testQueryWithMultipleLineComments2() throws SQLException { */ @Test public void testQueryWithMultipleLineCommentsInsert() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/insert /*test*/into " + charTable + " (c1) VALUES(?)"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/insert /*test*/into " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " (c1) VALUES(?)"); try { pstmt.getParameterMetaData(); @@ -1201,7 +1231,8 @@ public void testQueryWithMultipleLineCommentsInsert() throws SQLException { */ @Test public void testQueryWithMultipleLineCommentsUpdate() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/update /*test*/" + charTable + " set c1=123 where c1=?"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/update /*test*/" + + AbstractSQLGenerator.escapeIdentifier(charTable) + " set c1=123 where c1=?"); try { pstmt.getParameterMetaData(); @@ -1217,7 +1248,8 @@ public void testQueryWithMultipleLineCommentsUpdate() throws SQLException { */ @Test public void testQueryWithMultipleLineCommentsDeletion() throws SQLException { - pstmt = connection.prepareStatement("/*te\nst*//*test*/delete /*test*/from " + charTable + " where c1=?"); + pstmt = connection.prepareStatement("/*te\nst*//*test*/delete /*test*/from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1=?"); try { pstmt.getParameterMetaData(); @@ -1233,7 +1265,8 @@ public void testQueryWithMultipleLineCommentsDeletion() throws SQLException { */ @Test public void testQueryWithSingleLineComments1() throws SQLException { - pstmt = connection.prepareStatement("-- #test \n select top 100 c1 from " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement("-- #test \n select top 100 c1 from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1251,7 +1284,8 @@ public void testQueryWithSingleLineComments1() throws SQLException { */ @Test public void testQueryWithSingleLineComments2() throws SQLException { - pstmt = connection.prepareStatement("--#test\nselect top 100 c1 from " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement("--#test\nselect top 100 c1 from " + + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1269,7 +1303,8 @@ public void testQueryWithSingleLineComments2() throws SQLException { */ @Test public void testQueryWithSingleLineComments3() throws SQLException { - pstmt = connection.prepareStatement("select top 100 c1\nfrom " + charTable + " where c1 = ?"); + pstmt = connection.prepareStatement( + "select top 100 c1\nfrom " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1 = ?"); pstmt.setString(1, "abc"); try { @@ -1287,7 +1322,8 @@ public void testQueryWithSingleLineComments3() throws SQLException { */ @Test public void testQueryWithSingleLineCommentsInsert() throws SQLException { - pstmt = connection.prepareStatement("--#test\ninsert /*test*/into " + charTable + " (c1) VALUES(?)"); + pstmt = connection.prepareStatement( + "--#test\ninsert /*test*/into " + AbstractSQLGenerator.escapeIdentifier(charTable) + " (c1) VALUES(?)"); try { pstmt.getParameterMetaData(); @@ -1303,7 +1339,8 @@ public void testQueryWithSingleLineCommentsInsert() throws SQLException { */ @Test public void testQueryWithSingleLineCommentsUpdate() throws SQLException { - pstmt = connection.prepareStatement("--#test\nupdate /*test*/" + charTable + " set c1=123 where c1=?"); + pstmt = connection.prepareStatement("--#test\nupdate /*test*/" + + AbstractSQLGenerator.escapeIdentifier(charTable) + " set c1=123 where c1=?"); try { pstmt.getParameterMetaData(); @@ -1319,7 +1356,8 @@ public void testQueryWithSingleLineCommentsUpdate() throws SQLException { */ @Test public void testQueryWithSingleLineCommentsDeletion() throws SQLException { - pstmt = connection.prepareStatement("--#test\ndelete /*test*/from " + charTable + " where c1=?"); + pstmt = connection.prepareStatement( + "--#test\ndelete /*test*/from " + AbstractSQLGenerator.escapeIdentifier(charTable) + " where c1=?"); try { pstmt.getParameterMetaData(); @@ -1335,7 +1373,8 @@ public void testQueryWithSingleLineCommentsDeletion() throws SQLException { */ @Test public void testQueryWithSpaceAndEndCommentMarkInColumnName() throws SQLException { - pstmt = connection.prepareStatement("SELECT [c1*/someString withspace] from " + spaceTable); + pstmt = connection.prepareStatement( + "SELECT [c1*/someString withspace] from " + AbstractSQLGenerator.escapeIdentifier(spaceTable)); try { pstmt.getParameterMetaData(); @@ -1351,8 +1390,9 @@ public void testQueryWithSpaceAndEndCommentMarkInColumnName() throws SQLExceptio */ @Test public void testComplexQueryWithMultipleTables() throws SQLException { - pstmt = connection.prepareStatement("insert into " + charTable - + " (c1) select ? where not exists (select * from " + charTable2 + " where table2c1 = ?)"); + pstmt = connection.prepareStatement("insert into " + AbstractSQLGenerator.escapeIdentifier(charTable) + + " (c1) select ? where not exists (select * from " + AbstractSQLGenerator.escapeIdentifier(charTable2) + + " where table2c1 = ?)"); try { SQLServerParameterMetaData pMD = (SQLServerParameterMetaData) pstmt.getParameterMetaData(); @@ -1371,17 +1411,16 @@ public void testComplexQueryWithMultipleTables() throws SQLException { */ @AfterAll public static void dropTables() throws SQLException { - TestUtils.dropTableIfExists(nameTable, stmt); - TestUtils.dropTableIfExists(phoneNumberTable, stmt); - TestUtils.dropTableIfExists(mergeNameDesTable, stmt); - TestUtils.dropTableIfExists(numericTable, stmt); - TestUtils.dropTableIfExists(phoneNumberTable, stmt); - TestUtils.dropTableIfExists(charTable, stmt); - TestUtils.dropTableIfExists(charTable2, stmt); - TestUtils.dropTableIfExists(binaryTable, stmt); - TestUtils.dropTableIfExists(dateAndTimeTable, stmt); - TestUtils.dropTableIfExists(multipleTypesTable, stmt); - TestUtils.dropTableIfExists(spaceTable, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(nameTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(phoneNumberTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(mergeNameDesTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(numericTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(charTable2), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(binaryTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(dateAndTimeTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(multipleTypesTable), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(spaceTable), stmt); if (null != rs) { rs.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java index 7aca2f8755..e2ff2b7038 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PreparedStatementTest.java @@ -28,15 +28,21 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; @RunWith(JUnitPlatform.class) public class PreparedStatementTest extends AbstractTest { + + final String tableName = RandomUtil.getIdentifier("#update1"); + final String tableName2 = RandomUtil.getIdentifier("#update2"); + private void executeSQL(SQLServerConnection conn, String sql) throws SQLException { Statement stmt = conn.createStatement(); stmt.execute(sql); @@ -534,9 +540,6 @@ private void testStatementPoolingInternal(String mode) throws Exception { pstmt.getMoreResults(); // Make sure handle is updated. } } - System.out.println(String.format("Prep on first call: %s Query count:%s: %s of %s (%s)", - prepOnFirstCall, queryCount, testsWithHandleReuse, testCount, - (double) testsWithHandleReuse / (double) testCount)); } } } @@ -550,9 +553,11 @@ private void testStatementPoolingInternal(String mode) throws Exception { this.executeSQL(con, "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';"); // Test with missing handle failures (fake). - this.executeSQL(con, "CREATE TABLE #update1 (col INT);INSERT #update1 VALUES (1);"); - this.executeSQL(con, - "CREATE PROC #updateProc1 AS UPDATE #update1 SET col += 1; IF EXISTS (SELECT * FROM #update1 WHERE col % 5 = 0) RAISERROR(99586,16,1);"); + this.executeSQL(con, "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col INT);INSERT " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (1);"); + this.executeSQL(con, "CREATE PROC #updateProc1 AS UPDATE " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col += 1; IF EXISTS (SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col % 5 = 0) RAISERROR(99586,16,1);"); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc1")) { for (int i = 0; i < 100; ++i) { try { @@ -571,7 +576,8 @@ private void testStatementPoolingInternal(String mode) throws Exception { // test updated value, should be 1 + 100 = 101 // although executeUpdate() throws exception, update operation should be executed successfully. - try (ResultSet rs = con.createStatement().executeQuery("select * from #update1")) { + try (ResultSet rs = con.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName) + "")) { rs.next(); assertSame(101, rs.getInt(1)); } @@ -579,9 +585,11 @@ private void testStatementPoolingInternal(String mode) throws Exception { // Test batching with missing handle failures (fake). this.executeSQL(con, "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';"); - this.executeSQL(con, "CREATE TABLE #update2 (col INT);INSERT #update2 VALUES (1);"); - this.executeSQL(con, - "CREATE PROC #updateProc2 AS UPDATE #update2 SET col += 1; IF EXISTS (SELECT * FROM #update2 WHERE col % 5 = 0) RAISERROR(99586,16,1);"); + this.executeSQL(con, "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName2) + + " (col INT);INSERT " + AbstractSQLGenerator.escapeIdentifier(tableName2) + " VALUES (1);"); + this.executeSQL(con, "CREATE PROC #updateProc2 AS UPDATE " + + AbstractSQLGenerator.escapeIdentifier(tableName2) + " SET col += 1; IF EXISTS (SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName2) + " WHERE col % 5 = 0) RAISERROR(99586,16,1);"); try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc2")) { for (int i = 0; i < 100; ++i) { pstmt.addBatch(); @@ -605,7 +613,8 @@ private void testStatementPoolingInternal(String mode) throws Exception { // test updated value, should be 1 + 100 = 101 // although executeBatch() throws exception, update operation should be executed successfully. - try (ResultSet rs = con.createStatement().executeQuery("select * from #update2")) { + try (ResultSet rs = con.createStatement() + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName2) + "")) { rs.next(); assertSame(101, rs.getInt(1)); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java index 695155a9ca..2daad278f2 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTest.java @@ -21,18 +21,20 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; +import com.microsoft.sqlserver.jdbc.RandomUtil; import com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.TestResource; import com.microsoft.sqlserver.jdbc.TestUtils; +import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; @RunWith(JUnitPlatform.class) public class RegressionTest extends AbstractTest { - private static String tableName = "[ServerCursorPStmt]"; - private static String procName = "[ServerCursorProc]"; + private static String tableName; + private static String procName = RandomUtil.getIdentifier("ServerCursorProc"); /** * Tests select into stored proc @@ -49,32 +51,41 @@ public void testServerCursorPStmt() throws SQLException { String col3Value = "India"; String col3Lookup = "IN"; + tableName = RandomUtil.getIdentifier("ServerCursorPStmt"); + + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); + stmt.executeUpdate( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (1, 'CAN', 'Canada')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (2, 'USA', 'United States of America')"); stmt.executeUpdate( - "CREATE TABLE " + tableName + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (1, 'CAN', 'Canada')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (2, 'USA', 'United States of America')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (3, 'JPN', 'Japan')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (4, '" + col3Lookup + "', '" + col3Value + "')"); + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (3, 'JPN', 'Japan')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (4, '" + + col3Lookup + "', '" + col3Value + "')"); // create stored proc String storedProcString; if (DBConnection.isSqlAzure(con)) { // On SQL Azure, 'SELECT INTO' is not supported. So do not use it. - storedProcString = "CREATE PROCEDURE " + procName + " @param varchar(3) AS SELECT col3 FROM " - + tableName + " WHERE col2 = @param"; + storedProcString = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @param varchar(3) AS SELECT col3 FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " WHERE col2 = @param"; } else { // On SQL Server - storedProcString = "CREATE PROCEDURE " + procName - + " @param varchar(3) AS SELECT col3 INTO #TMPTABLE FROM " + tableName + storedProcString = "CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @param varchar(3) AS SELECT col3 INTO #TMPTABLE FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col2 = @param SELECT col3 FROM #TMPTABLE"; } stmt.executeUpdate(storedProcString); // execute stored proc via pstmt - try (PreparedStatement pstmt = con.prepareStatement("EXEC " + procName + " ?", - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { + try (PreparedStatement pstmt = con.prepareStatement( + "EXEC " + AbstractSQLGenerator.escapeIdentifier(procName) + " ?", ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { pstmt.setString(1, col3Lookup); // should return 1 row @@ -88,6 +99,8 @@ public void testServerCursorPStmt() throws SQLException { TestResource.getResource("R_valueNotMatch") + rs.getString(1) + ", " + col3Value); } } + } finally { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -103,23 +116,28 @@ public void testSelectIntoUpdateCount() throws SQLException { // Azure does not do SELECT INTO if (!DBConnection.isSqlAzure(con)) { - final String tableName = "[#SourceTableForSelectInto]"; + tableName = RandomUtil.getIdentifier("[#SourceTableForSelectInto]]"); try (Statement stmt = con.createStatement()) { - stmt.executeUpdate("CREATE TABLE " + tableName + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int primary key, col2 varchar(3), col3 varchar(128))"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (1, 'CAN', 'Canada')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (2, 'USA', 'United States of America')"); - stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (3, 'JPN', 'Japan')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (1, 'CAN', 'Canada')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (2, 'USA', 'United States of America')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " VALUES (3, 'JPN', 'Japan')"); // expected values int numRowsToCopy = 2; - try (PreparedStatement ps = con - .prepareStatement("SELECT * INTO #TMPTABLE FROM " + tableName + " WHERE col1 <= ?")) { + try (PreparedStatement ps = con.prepareStatement("SELECT * INTO #TMPTABLE FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 <= ?")) { ps.setInt(1, numRowsToCopy); int updateCount = ps.executeUpdate(); assertEquals(numRowsToCopy, updateCount, TestResource.getResource("R_incorrectUpdateCount")); + } finally { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } @@ -141,16 +159,16 @@ public void testUpdateQuery() throws SQLException { String sql; JDBCType[] targets = {JDBCType.INTEGER, JDBCType.SMALLINT}; int rows = 3; - final String tableName = "[updateQuery]"; + tableName = RandomUtil.getIdentifier("[updateQuery]"); - TestUtils.dropTableIfExists(tableName, stmt); - stmt.executeUpdate( - "CREATE TABLE " + tableName + " (" + "c1 int null," + "PK int NOT NULL PRIMARY KEY" + ")"); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (" + + "c1 int null," + "PK int NOT NULL PRIMARY KEY" + ")"); /* * populate table */ - sql = "insert into " + tableName + " values(" + "?,?" + ")"; + sql = "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(" + "?,?" + ")"; try (PreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, con.getHoldability())) { @@ -163,7 +181,7 @@ public void testUpdateQuery() throws SQLException { /* * Update table */ - sql = "update " + tableName + " SET c1= ? where PK =1"; + sql = "update " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET c1= ? where PK =1"; for (int i = 1; i <= rows; i++) { try (PreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { @@ -177,15 +195,16 @@ public void testUpdateQuery() throws SQLException { /* * Verify */ - try (ResultSet rs = stmt.executeQuery("select * from " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("select * from " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); assertEquals(rs.getInt(1), 8, "Value mismatch"); + } finally { + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } } } - private String xmlTableName = "try_SQLXML_Table"; - /** * Tests XML query * @@ -198,16 +217,18 @@ public void testXmlQuery() throws SQLException { try (Connection connection = DriverManager.getConnection(connectionString); Statement stmt = connection.createStatement()) { - dropTables(stmt); + TestUtils.dropTableIfExists(tableName, stmt); createTable(stmt); - String sql = "UPDATE " + xmlTableName + " SET [c2] = ?, [c3] = ?"; - try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { + tableName = RandomUtil.getIdentifier("try_SQLXML_Table"); + String sql = "UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET [c2] = ?, [c3] = ?"; + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { pstmt.setObject(1, null); pstmt.setObject(2, null, Types.SQLXML); pstmt.executeUpdate(); } + try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) connection.prepareStatement(sql)) { pstmt.setObject(1, null, Types.SQLXML); pstmt.setObject(2, null); @@ -218,17 +239,16 @@ public void testXmlQuery() throws SQLException { pstmt.setObject(1, null); pstmt.setObject(2, null, Types.SQLXML); pstmt.executeUpdate(); + } finally { + TestUtils.dropTableIfExists(tableName, stmt); } } } - private void dropTables(Statement stmt) throws SQLException { - stmt.executeUpdate("if object_id('" + xmlTableName + "','U') is not null" + " drop table " + xmlTableName); - } - private void createTable(Statement stmt) throws SQLException { - String sql = "CREATE TABLE " + xmlTableName + " ([c1] int, [c2] xml, [c3] xml)"; + String sql = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " ([c1] int, [c2] xml, [c3] xml)"; stmt.execute(sql); } @@ -238,7 +258,7 @@ public static void terminate() throws SQLException { try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTestAlwaysEncrypted.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTestAlwaysEncrypted.java deleted file mode 100644 index 005a40e01e..0000000000 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/RegressionTestAlwaysEncrypted.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made - * available under the terms of the MIT License. See the LICENSE file in the project root for more information. - */ -/* TODO: Make possible to run automated (including certs, only works on Windows now etc.) */ -/* - * package com.microsoft.sqlserver.jdbc.unit.statement; import static org.junit.jupiter.api.Assertions.assertTrue; - * import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.JDBCType; import - * java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.jupiter.api.Test; - * import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import - * com.microsoft.sqlserver.jdbc.SQLServerConnection; import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; - * import com.microsoft.sqlserver.jdbc.SQLServerResultSet; import com.microsoft.sqlserver.testframework.AbstractTest; - * @RunWith(JUnitPlatform.class) public class RegressionTestAlwaysEncrypted extends AbstractTest { String dateTable = - * "DateTable"; String charTable = "CharTable"; String numericTable = "NumericTable"; Statement stmt = null; Connection - * connection = null; Date date; String cekName = "CEK_Auto1"; // you need to change this to your CEK long dateValue = - * 212921879801519L; - * @Test public void alwaysEncrypted1() throws Exception { - * Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); connection = - * DriverManager.getConnection(connectionString + - * ";trustservercertificate=true;columnEncryptionSetting=enabled;database=Tobias;"); assertTrue(null != connection); - * stmt = ((SQLServerConnection) connection).createStatement(); date = new Date(dateValue); dropTable(); - * createNumericTable(); populateNumericTable(); printNumericTable(); dropTable(); createDateTable(); - * populateDateTable(); printDateTable(); dropTable(); createNumericTable(); populateNumericTableWithNull(); - * printNumericTable(); } - * @Test public void alwaysEncrypted2() throws Exception { - * Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); connection = - * DriverManager.getConnection(connectionString + - * ";trustservercertificate=true;columnEncryptionSetting=enabled;database=Tobias;"); assertTrue(null != connection); - * stmt = ((SQLServerConnection) connection).createStatement(); date = new Date(dateValue); dropTable(); - * createCharTable(); populateCharTable(); printCharTable(); dropTable(); createDateTable(); populateDateTable(); - * printDateTable(); dropTable(); createNumericTable(); populateNumericTableSpecificSetter(); printNumericTable(); } - * private void populateDateTable() { try { String sql = "insert into " + dateTable + " values( " + "?" + ")"; - * SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) ((SQLServerConnection) - * connection).prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, - * connection.getHoldability()); sqlPstmt.setObject(1, date); sqlPstmt.executeUpdate(); } catch (Exception e) { - * e.printStackTrace(); } } private void populateCharTable() { try { String sql = "insert into " + charTable + - * " values( " + "?,?,?,?,?,?" + ")"; SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) - * ((SQLServerConnection) connection).prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, - * connection.getHoldability()); sqlPstmt.setObject(1, "hi"); sqlPstmt.setObject(2, "sample"); sqlPstmt.setObject(3, - * "hey"); sqlPstmt.setObject(4, "test"); sqlPstmt.setObject(5, "hello"); sqlPstmt.setObject(6, "caching"); - * sqlPstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } private void populateNumericTable() throws - * Exception { String sql = "insert into " + numericTable + " values( " + "?,?,?,?,?,?,?,?,?" + ")"; - * SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) ((SQLServerConnection) - * connection).prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, - * connection.getHoldability()); sqlPstmt.setObject(1, true); sqlPstmt.setObject(2, false); sqlPstmt.setObject(3, true); - * Integer value = 255; sqlPstmt.setObject(4, value.shortValue(), JDBCType.TINYINT); sqlPstmt.setObject(5, - * value.shortValue(), JDBCType.TINYINT); sqlPstmt.setObject(6, value.shortValue(), JDBCType.TINYINT); - * sqlPstmt.setObject(7, Short.valueOf("1"), JDBCType.SMALLINT); sqlPstmt.setObject(8, Short.valueOf("2"), - * JDBCType.SMALLINT); sqlPstmt.setObject(9, Short.valueOf("3"), JDBCType.SMALLINT); sqlPstmt.executeUpdate(); } private - * void populateNumericTableSpecificSetter() { try { String sql = "insert into " + numericTable + " values( " + - * "?,?,?,?,?,?,?,?,?" + ")"; SQLServerPreparedStatement sqlPstmt = (SQLServerPreparedStatement) ((SQLServerConnection) - * connection).prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, - * connection.getHoldability()); sqlPstmt.setBoolean(1, true); sqlPstmt.setBoolean(2, false); sqlPstmt.setBoolean(3, - * true); Integer value = 255; sqlPstmt.setShort(4, value.shortValue()); sqlPstmt.setShort(5, value.shortValue()); - * sqlPstmt.setShort(6, value.shortValue()); sqlPstmt.setByte(7, Byte.valueOf("127")); sqlPstmt.setByte(8, - * Byte.valueOf("127")); sqlPstmt.setByte(9, Byte.valueOf("127")); sqlPstmt.executeUpdate(); } catch (Exception e) { - * e.printStackTrace(); } } private void populateNumericTableWithNull() { try { String sql = "insert into " + - * numericTable + " values( " + "?,?,?" + ",?,?,?" + ",?,?,?" + ")"; SQLServerPreparedStatement sqlPstmt = - * (SQLServerPreparedStatement) ((SQLServerConnection) connection).prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, - * ResultSet.CONCUR_READ_ONLY, connection.getHoldability()); sqlPstmt.setObject(1, null, java.sql.Types.BIT); - * sqlPstmt.setObject(2, null, java.sql.Types.BIT); sqlPstmt.setObject(3, null, java.sql.Types.BIT); - * sqlPstmt.setObject(4, null, java.sql.Types.TINYINT); sqlPstmt.setObject(5, null, java.sql.Types.TINYINT); - * sqlPstmt.setObject(6, null, java.sql.Types.TINYINT); sqlPstmt.setObject(7, null, java.sql.Types.SMALLINT); - * sqlPstmt.setObject(8, null, java.sql.Types.SMALLINT); sqlPstmt.setObject(9, null, java.sql.Types.SMALLINT); - * sqlPstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } private void printDateTable() throws - * SQLException { stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - * SQLServerResultSet rs = (SQLServerResultSet) stmt.executeQuery("select * from " + dateTable); while (rs.next()) { - * System.out.println(rs.getObject(1)); } } private void printCharTable() throws SQLException { stmt = - * connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); SQLServerResultSet rs = - * (SQLServerResultSet) stmt.executeQuery("select * from " + charTable); while (rs.next()) { - * System.out.println(rs.getObject(1)); System.out.println(rs.getObject(2)); System.out.println(rs.getObject(3)); - * System.out.println(rs.getObject(4)); System.out.println(rs.getObject(5)); System.out.println(rs.getObject(6)); } } - * private void printNumericTable() throws SQLException { stmt = - * connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); SQLServerResultSet rs = - * (SQLServerResultSet) stmt.executeQuery("select * from " + numericTable); while (rs.next()) { - * System.out.println(rs.getObject(1)); System.out.println(rs.getObject(2)); System.out.println(rs.getObject(3)); - * System.out.println(rs.getObject(4)); System.out.println(rs.getObject(5)); System.out.println(rs.getObject(6)); } } - * private void createDateTable() throws SQLException { String sql = "create table " + dateTable + " (" + - * "RandomizedDate date ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + ");"; try { stmt.execute(sql); } catch (SQLException e) { System.out.println(e); } } private - * void createCharTable() throws SQLException { String sql = "create table " + charTable + " (" + - * "PlainChar char(20) null," + - * "RandomizedChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + - * "DeterministicChar char(20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") 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," + - * "DeterministicVarchar varchar(50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + ");"; try { stmt.execute(sql); } catch (SQLException e) { System.out.println(e.getMessage()); - * } } private void createNumericTable() throws SQLException { String sql = "create table " + numericTable + " (" + - * "PlainBit bit null," + - * "RandomizedBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + - * "DeterministicBit bit ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + "PlainTinyint tinyint null," + - * "RandomizedTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + - * "DeterministicTinyint tinyint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + "PlainSmallint smallint null," + - * "RandomizedSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + - * "DeterministicSmallint smallint ENCRYPTED WITH (ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256', COLUMN_ENCRYPTION_KEY = " - * + cekName + ") NULL," + ");"; try { stmt.execute(sql); } catch (SQLException e) { System.out.println(e.getMessage()); - * } } private void dropTable() throws SQLException { stmt.executeUpdate("if object_id('" + dateTable + - * "','U') is not null" + " drop table " + dateTable); stmt.executeUpdate("if object_id('" + charTable + - * "','U') is not null" + " drop table " + charTable); stmt.executeUpdate("if object_id('" + numericTable + - * "','U') is not null" + " drop table " + numericTable); } } - */ 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 ab30549632..b43dd312e7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java @@ -70,8 +70,7 @@ public class TCAttentionHandling { + " It is particularly long so that we will get a multipacket TDS response back from the server." + " This is a test string." + " This is a test string." + " This is a test string." + " This is a test string." + " This is a test string." + " This is a test string."; - String tableN = RandomUtil.getIdentifier("TCAttentionHandling"); - String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); + String tableName = RandomUtil.getIdentifier("TCAttentionHandling"); @BeforeEach public void init() throws Exception { @@ -79,13 +78,13 @@ public void init() throws Exception { con.setAutoCommit(false); try (Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT PRIMARY KEY, col2 VARCHAR(" - + TEST_STRING.length() + "))"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 INT PRIMARY KEY, col2 VARCHAR(" + TEST_STRING.length() + "))"); for (int i = 0; i < NUM_TABLE_ROWS; i++) - stmt.executeUpdate( - "INSERT INTO " + tableName + " (col1, col2) VALUES (" + i + ", '" + TEST_STRING + "')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1, col2) VALUES (" + i + ", '" + TEST_STRING + "')"); } con.commit(); } @@ -96,7 +95,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} } } @@ -112,7 +111,8 @@ public void testCancelBeforeExecute() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { stmt.cancel(); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { int numSelectedRows = 0; while (rs.next()) ++numSelectedRows; @@ -134,8 +134,9 @@ public void testCancelBeforeExecute() throws Exception { */ @Test public void testErrorInRequest() throws Exception { - try (Connection con = DriverManager.getConnection(connectionString); PreparedStatement ps = con - .prepareStatement("UPDATE " + tableName + " SET col2 = ? WHERE col1 = ?")) { + try (Connection con = DriverManager.getConnection(connectionString); + PreparedStatement ps = con.prepareStatement("UPDATE " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " SET col2 = ? WHERE col1 = ?")) { ps.setString(1, TEST_STRING); for (int i = 0; i < MIN_TABLE_ROWS; i++) { ps.setInt(2, i); @@ -233,7 +234,8 @@ public void testCancelLongResponse() throws Exception { } try (ResultSet rs = stmt.executeQuery( - "SELECT " + "a.col1, a.col2 FROM " + tableName + " a CROSS JOIN " + tableName + " b")) { + "SELECT " + "a.col1, a.col2 FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " a CROSS JOIN " + AbstractSQLGenerator.escapeIdentifier(tableName) + " b")) { // Scan the first MIN_TABLE_ROWS rows int numSelectedRows = 0; @@ -311,8 +313,8 @@ public void testCancelBlockedResponse() throws Exception { // and leave it non-responsive for now... conLock.setAutoCommit(false); try (Statement stmtLock = conLock.createStatement()) { - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " SET col2 = 'New Value!' WHERE col1 = " + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); try (Connection con = DriverManager.getConnection(connectionString)) { // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options @@ -339,7 +341,8 @@ public void testCancelBlockedResponse() throws Exception { try (Statement stmt = con.createStatement(SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt.executeQuery( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { // Time how long it takes for execution to be cancelled... long elapsedMillis = -System.currentTimeMillis(); @@ -402,8 +405,8 @@ public void testCancelBlockedResponsePS() throws Exception { // and leave it non-responsive for now... conLock.setAutoCommit(false); try (Statement stmtLock = conLock.createStatement()) { - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " SET col2 = 'New Value!' WHERE col1 = " + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); try (Connection con = DriverManager.getConnection(connectionString)) { // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options @@ -426,7 +429,8 @@ public void testCancelBlockedResponsePS() throws Exception { // // Need to use adaptive response buffering when executing the statement. // Otherwise, we would block in executeQuery()... - try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM " + tableName, + try (PreparedStatement stmt = con.prepareStatement( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName), SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { ((SQLServerStatement) stmt).setResponseBuffering("adaptive"); try (ResultSet rs = stmt.executeQuery()) { @@ -496,8 +500,8 @@ public void testCancelBlockedCursoredResponse() throws Exception { // and leave it non-responsive for now... conLock.setAutoCommit(false); try (Statement stmtLock = conLock.createStatement()) { - stmtLock.executeUpdate("UPDATE " + tableName + " SET col2 = 'New Value!' WHERE col1 = " - + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); + stmtLock.executeUpdate("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " SET col2 = 'New Value!' WHERE col1 = " + (NUM_TABLE_ROWS - MIN_TABLE_ROWS)); try (Connection con = DriverManager.getConnection(connectionString)) { // In SQL Azure, both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT options @@ -515,7 +519,8 @@ public void testCancelBlockedCursoredResponse() throws Exception { con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); } - try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM " + tableName, + try (PreparedStatement stmt = con.prepareStatement( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName), SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { // Start up a thread to cancel the following SELECT after 3 seconds of blocking. @@ -577,7 +582,8 @@ public void testCancelAfterResponse() throws Exception { int numSelectedRows; try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { numSelectedRows = 0; while (rs.next()) ++numSelectedRows; @@ -589,7 +595,8 @@ public void testCancelAfterResponse() throws Exception { stmt.cancel(); // Verify that the query can be re-executed without error - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { numSelectedRows = 0; while (rs.next()) ++numSelectedRows; @@ -606,18 +613,19 @@ public void testCancelAfterResponse() throws Exception { public void testCancelGetOutParams() throws Exception { // Use small packet size to force OUT params to span multiple packets // so that cancelling execution from the same thread will work. - String name = RandomUtil.getIdentifier("p1"); - final String procName = AbstractSQLGenerator.escapeIdentifier(name); + final String procName = RandomUtil.getIdentifier("p1"); try (Connection con = DriverManager.getConnection(connectionString + ";packetSize=512"); Statement stmt = con.createStatement()) { try { - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (Exception ex) {} ; - stmt.executeUpdate("CREATE PROCEDURE " + procName + " @arg1 CHAR(512) OUTPUT, " - + " @arg2 CHAR(512) OUTPUT, " + " @arg3 CHAR(512) OUTPUT " + "AS " + "BEGIN " - + " SET @arg1='hi' " + " SET @arg2='there' " + " SET @arg3='!' " + "END"); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?, ?)}")) { + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @arg1 CHAR(512) OUTPUT, " + " @arg2 CHAR(512) OUTPUT, " + + " @arg3 CHAR(512) OUTPUT " + "AS " + "BEGIN " + " SET @arg1='hi' " + + " SET @arg2='there' " + " SET @arg3='!' " + "END"); + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?, ?)}")) { ((SQLServerStatement) cstmt).setResponseBuffering("adaptive"); cstmt.registerOutParameter(1, Types.CHAR); cstmt.registerOutParameter(2, Types.CHAR); @@ -646,7 +654,7 @@ public void testCancelGetOutParams() throws Exception { // Reexecute to prove CS is still good after last cancel cstmt.execute(); } - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } } @@ -710,7 +718,8 @@ void start(final Connection con) { public void run() { ++numExecuteTries; - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = stmt.executeQuery( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { while (rs.next()) ++numExecuteSuccesses; @@ -880,10 +889,8 @@ public void testCloseOnCompletion() throws Exception { @Nested public class TCStatement { - String tableNTemp = RandomUtil.getIdentifier("TCStatement1"); - private final String table1Name = AbstractSQLGenerator.escapeIdentifier(tableNTemp); - String table2NameTemp = RandomUtil.getIdentifier("TCStatement2"); - private final String table2Name = AbstractSQLGenerator.escapeIdentifier(table2NameTemp); + private final String table1Name = RandomUtil.getIdentifier("TCStatement1"); + private final String table2Name = RandomUtil.getIdentifier("TCStatement2"); /** * test statement.closeOnCompltetion method @@ -953,16 +960,19 @@ public void testConsecutiveQueries() throws Exception { } try { - TestUtils.dropTableIfExists(table1Name, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1Name), stmt); } catch (SQLException e) {} try { - TestUtils.dropTableIfExists(table2Name, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); } catch (SQLException e) {} - stmt.executeUpdate("CREATE TABLE " + table1Name + " (col1 INT PRIMARY KEY)"); - stmt.executeUpdate("CREATE TABLE " + table2Name + " (col1 INT PRIMARY KEY)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table1Name) + + " (col1 INT PRIMARY KEY)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (col1 INT PRIMARY KEY)"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + table2Name)) {} catch (Exception e) { + try (ResultSet rs = stmt.executeQuery( + "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(table2Name))) {} catch (Exception e) { assertEquals(stmt.isClosed(), true, TestResource.getResource("R_statementShouldBeClosed")); } } @@ -1055,8 +1065,8 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - TestUtils.dropTableIfExists(table1Name, stmt); - TestUtils.dropTableIfExists(table2Name, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table1Name), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); } catch (SQLException e) {} } } @@ -1064,8 +1074,7 @@ public void terminate() throws Exception { @Nested public class TCStatementCallable { - String name = RandomUtil.getIdentifier("p1"); - String procName = AbstractSQLGenerator.escapeIdentifier(name); + String procName = RandomUtil.getIdentifier("p1"); /** * Tests CallableStatementMethods on jdbc41 @@ -1078,10 +1087,10 @@ public void testJdbc41CallableStatementMethods() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - String query = "create procedure " + procName + " @col1Value varchar(512) OUTPUT," - + " @col2Value int OUTPUT," + " @col3Value float OUTPUT," + " @col4Value decimal(10,5) OUTPUT," - + " @col5Value uniqueidentifier OUTPUT," + " @col6Value xml OUTPUT," - + " @col7Value varbinary(max) OUTPUT," + " @col8Value text OUTPUT," + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col1Value varchar(512) OUTPUT," + " @col2Value int OUTPUT," + " @col3Value float OUTPUT," + + " @col4Value decimal(10,5) OUTPUT," + " @col5Value uniqueidentifier OUTPUT," + + " @col6Value xml OUTPUT," + " @col7Value varbinary(max) OUTPUT," + " @col8Value text OUTPUT," + " @col9Value ntext OUTPUT," + " @col10Value varbinary(max) OUTPUT," + " @col11Value date OUTPUT," + " @col12Value time OUTPUT," + " @col13Value datetime2 OUTPUT," + " @col14Value datetimeoffset OUTPUT," + " @col15Value decimal(10,10) OUTPUT," @@ -1098,7 +1107,8 @@ public void testJdbc41CallableStatementMethods() throws Exception { // Test JDBC 4.1 methods for CallableStatement try (CallableStatement cstmt = conn - .prepareCall("{call " + procName + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}")) { + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}")) { cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); cstmt.registerOutParameter(2, java.sql.Types.INTEGER); cstmt.registerOutParameter(3, java.sql.Types.FLOAT); @@ -1212,7 +1222,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1223,10 +1233,8 @@ public void terminate() throws Exception { @Nested public class TCStatementParam { - String tableNameTemp = RandomUtil.getIdentifier("TCStatementParam"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); - String procNameTemp = "TCStatementParam"; - private final String procName = AbstractSQLGenerator.escapeIdentifier(procNameTemp); + private final String tableName = RandomUtil.getIdentifier("TCStatementParam"); + private final String procName = RandomUtil.getIdentifier("TCStatementParam"); /** * @@ -1244,7 +1252,7 @@ public void testStatementOutParamGetsTwice() throws Exception { log.fine("testStatementOutParamGetsTwice threw: " + e.getMessage()); } - stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); try (ResultSet rs = stmt.getResultSet()) { @@ -1256,7 +1264,8 @@ public void testStatementOutParamGetsTwice() throws Exception { } } - try (CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?,?)}")) { cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1284,10 +1293,11 @@ public void testStatementOutParamGetsTwice() throws Exception { public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT, @p4_smallint smallint OUTPUT, @p5_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint, @p5_smallint_out=@p4_smallint RETURN @p2_smallint + 1"); - try (CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?, ?, ?)}")) { + try (CallableStatement cstmt = con.prepareCall( + "{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?,?, ?, ?)}")) { cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1317,10 +1327,11 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { public void testStatementOutParamGetsTwiceInOut() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + stmt.executeUpdate("CREATE PROCEDURE " + AbstractSQLGenerator.escapeIdentifier(procName) + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p3_smallint_out +1 RETURN @p2_smallint + 1"); - try (CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{ ? = CALL " + AbstractSQLGenerator.escapeIdentifier(procName) + " (?,?)}")) { cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("1"), Types.SMALLINT); cstmt.setObject(3, Short.valueOf("100"), Types.SMALLINT); @@ -1347,16 +1358,20 @@ public void testResultSetParams() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate( - "create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); - stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); - stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); - String query = "create procedure " + procName - + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + tableName + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hello')"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hi')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col1=@col1Value SET @col2Value='hi' END"; stmt.execute(query); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?)}")) { cstmt.setInt(1, 0); cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); try (ResultSet rs = cstmt.executeQuery()) { @@ -1378,16 +1393,20 @@ public void testResultSetNullParams() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hello')"); stmt.executeUpdate( - "create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); - stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); - stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); - String query = "create procedure " + procName - + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + tableName + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hi')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " where col1=@col1Value SET @col2Value='hi' END"; stmt.execute(query); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?)}")) { cstmt.setInt(1, 0); try { cstmt.getInt(2); @@ -1408,21 +1427,24 @@ public void testFailedToResumeTransaction() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); - stmt.executeUpdate("Insert into " + tableName + " values(0)"); - stmt.executeUpdate("Insert into " + tableName + " values(1)"); - stmt.executeUpdate("Insert into " + tableName + " values(2)"); - stmt.executeUpdate("Insert into " + tableName + " values(3)"); - try (PreparedStatement ps = con - .prepareStatement("BEGIN TRAN " + "Insert into " + tableName + " values(4) " + "ROLLBACK")) {} + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int primary key)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(1)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(2)"); + stmt.executeUpdate("Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(3)"); + try (PreparedStatement ps = con.prepareStatement("BEGIN TRAN " + "Insert into " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(4) " + "ROLLBACK")) {} con.setAutoCommit(false); - try (PreparedStatement ps2 = con.prepareStatement("Insert into " + tableName + " values('a')")) { + try (PreparedStatement ps2 = con.prepareStatement( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values('a')")) { try { ps2.execute(); } catch (SQLException e) {} try { - stmt.executeUpdate("Insert into " + tableName + " values(4)"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(4)"); } catch (SQLException ex) {} } } @@ -1437,15 +1459,18 @@ public void testResultSetErrors() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { + stmt.executeUpdate("create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); + stmt.executeUpdate( + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hello')"); stmt.executeUpdate( - "create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); - stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); - stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); - String query = "create procedure " + procName - + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from somenonexistanttable where col1=@col1Value SET @col2Value='hi' END"; + "Insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0, 'hi')"); + String query = "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + + " @col1Value int, @col2Value varchar(512) OUTPUT AS BEGIN SELECT * from somenonexistenttable where col1=@col1Value SET @col2Value='hi' END"; stmt.execute(query); - try (CallableStatement cstmt = con.prepareCall("{call " + procName + "(?, ?)}")) { + try (CallableStatement cstmt = con + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?, ?)}")) { cstmt.setInt(1, 0); cstmt.registerOutParameter(2, Types.VARCHAR); @@ -1466,13 +1491,15 @@ public void testRowError() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { - stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); - stmt.executeUpdate("insert into " + tableName + " values(0)"); - stmt.executeUpdate("insert into " + tableName + " values(1)"); - stmt.executeUpdate("insert into " + tableName + " values(2)"); + stmt.executeUpdate( + "create table " + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1 int primary key)"); + stmt.executeUpdate("insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(0)"); + stmt.executeUpdate("insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(1)"); + stmt.executeUpdate("insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + " values(2)"); stmt.execute( - "create procedure " + procName + " @col1Value int AS " + " BEGIN " + " SELECT col1 FROM " - + tableName + " WITH (UPDLOCK) WHERE (col1 = @col1Value) " + " END"); + "create procedure " + AbstractSQLGenerator.escapeIdentifier(procName) + " @col1Value int AS " + + " BEGIN " + " SELECT col1 FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " WITH (UPDLOCK) WHERE (col1 = @col1Value) " + " END"); // For the test, lock each row in the table, one by one, for update // on one connection and, on another connection, verify that the @@ -1488,7 +1515,8 @@ public void testRowError() throws Exception { // locking it for update. try (Connection testConn1 = DriverManager.getConnection(connectionString)) { testConn1.setAutoCommit(false); - try (CallableStatement cstmt = testConn1.prepareCall("{call " + procName + "(?)}")) { + try (CallableStatement cstmt = testConn1 + .prepareCall("{call " + AbstractSQLGenerator.escapeIdentifier(procName) + "(?)}")) { cstmt.setInt(1, row); // enable isCloseOnCompletion @@ -1511,8 +1539,8 @@ public void testRowError() throws Exception { try (Statement stmt2 = testConn2.createStatement()) { stmt2.executeUpdate("SET LOCK_TIMEOUT 0"); - try (CallableStatement cstmt2 = testConn2 - .prepareCall("SELECT col1 FROM " + tableName + " WITH (UPDLOCK)")) { + try (CallableStatement cstmt2 = testConn2.prepareCall("SELECT col1 FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " WITH (UPDLOCK)")) { // Verify that the result set can be closed after // the lock timeout error @@ -1556,8 +1584,8 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropProcedureIfExists(procName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(procName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1567,8 +1595,7 @@ public void terminate() throws Exception { @Nested public class TCSparseColumnSetAndNBCROW { - String temp = RandomUtil.getIdentifier("TCStatementSparseColumnSetAndNBCROW"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(temp); + private final String tableName = RandomUtil.getIdentifier("TCStatementSparseColumnSetAndNBCROW"); private Connection createConnectionAndPopulateData() throws Exception { SQLServerDataSource ds = new SQLServerDataSource(); @@ -1580,9 +1607,9 @@ private Connection createConnectionAndPopulateData() throws Exception { Statement stmt = con.createStatement(); - stmt.executeUpdate("CREATE TABLE " + tableName + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + "(col1_int int PRIMARY KEY IDENTITY(1,1), col2_varchar varchar(200), col3_varchar varchar(20) SPARSE NULL, col4_smallint smallint SPARSE NULL, col5_xml XML COLUMN_SET FOR ALL_SPARSE_COLUMNS, col6_nvarcharMax NVARCHAR(MAX), col7_varcharMax VARCHAR(MAX))"); - stmt.executeUpdate("INSERT INTO " + tableName + " DEFAULT VALUES"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " DEFAULT VALUES"); assertTrue(con != null, "connection is null"); return con; @@ -1593,7 +1620,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -1616,7 +1643,7 @@ public void testNBCROWNullsForLOBs() throws Exception { try (Connection con = createConnectionAndPopulateData()) { Statement stmt = con.createStatement(); String selectQuery = "SELECT col1_int, col2_varchar, col3_varchar, col4_smallint, col5_xml, col6_nvarcharMax, col7_varcharMax FROM " - + tableName; + + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); @@ -1648,7 +1675,7 @@ public void testSparseColumnSetValues() throws Exception { try (Connection con = createConnectionAndPopulateData(); Statement stmt = con.createStatement()) { String selectQuery = "SELECT col1_int, col2_varchar, col3_varchar, col4_smallint, col5_xml, col6_nvarcharMax, col7_varcharMax FROM " - + tableName; + + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); @@ -1687,7 +1714,7 @@ public void testSparseColumnSetIndex() throws Exception { try (Connection con = createConnectionAndPopulateData(); Statement stmt = con.createStatement()) { String selectQuery = "SELECT col1_int, col2_varchar, col3_varchar, col4_smallint, col5_xml, col6_nvarcharMax, col7_varcharMax FROM " - + tableName; + + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); @@ -1726,7 +1753,7 @@ public void testSparseColumnSetForException() throws Exception { SQLServerResultSetMetaData rsmd; try (Connection con = createConnectionAndPopulateData(); Statement stmt = con.createStatement()) { - String selectQuery = "SELECT * FROM " + tableName; + String selectQuery = "SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName); try (ResultSet rs = stmt.executeQuery(selectQuery)) { rs.next(); rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); @@ -1738,7 +1765,8 @@ public void testSparseColumnSetForException() throws Exception { stmt.close(); rsmd.isSparseColumnSet(1); } - try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); con.close(); rsmd.isSparseColumnSet(1); @@ -1765,10 +1793,11 @@ public void testNBCRowForAllNulls() throws Exception { try (Connection con = ds.getConnection(); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} - String createTableQuery = "CREATE TABLE " + tableName + "(col1 int PRIMARY KEY IDENTITY(1,1)"; + String createTableQuery = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1 int PRIMARY KEY IDENTITY(1,1)"; int noOfColumns = 128; for (int i = 2; i <= noOfColumns; i++) { @@ -1776,8 +1805,10 @@ public void testNBCRowForAllNulls() throws Exception { } createTableQuery += ")"; stmt.executeUpdate(createTableQuery); - stmt.executeUpdate("INSERT INTO " + tableName + " DEFAULT VALUES"); - try (ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + stmt.executeUpdate( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " DEFAULT VALUES"); + try (ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { rs.next(); // test that all columns except the first one are null @@ -1816,11 +1847,12 @@ public void testNBCROWWithRandomAccess() throws Exception { try (Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) {} // construct a query to create a table with 100 columns - String createTableQuery = "CREATE TABLE " + tableName + "(col1 int PRIMARY KEY IDENTITY(1,1)"; + String createTableQuery = "CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1 int PRIMARY KEY IDENTITY(1,1)"; for (int i = 2; i <= noOfColumns; i++) { createTableQuery = createTableQuery + ", col" + i + " int"; @@ -1828,7 +1860,7 @@ public void testNBCROWWithRandomAccess() throws Exception { createTableQuery += ")"; stmt.executeUpdate(createTableQuery); - stmt.executeUpdate("TRUNCATE TABLE " + tableName); + stmt.executeUpdate("TRUNCATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName)); // randomly generate columns whose values would be set to a non null value nonNullColumns = new ArrayList<>(); @@ -1844,7 +1876,7 @@ public void testNBCROWWithRandomAccess() throws Exception { } // construct the insert query - String insertQuery = "INSERT INTO " + tableName + "("; + String insertQuery = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + "("; String values = " VALUES("; for (int i = 1; i < nonNullColumns.size(); i++) { insertQuery = insertQuery + "col" + nonNullColumns.get(i); @@ -1861,7 +1893,8 @@ public void testNBCROWWithRandomAccess() throws Exception { // if there are no non-null columns if (nonNullColumns.size() == 1) - insertQuery = "INSERT INTO " + tableName + " DEFAULT VALUES"; + insertQuery = "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " DEFAULT VALUES"; log.fine("INSEER Query:" + insertQuery); // populate the table by executing the insert query @@ -1871,7 +1904,8 @@ public void testNBCROWWithRandomAccess() throws Exception { } try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName)) { + ResultSet rs = stmt + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { // Try accessing rows and columns randomly for 10 times for (int j = 0; j < 10; j++) { @@ -2073,10 +2107,10 @@ public void testClosedConnection() throws Exception { public class TCUpdateCountWithTriggers { private static final int NUM_ROWS = 3; - private final String tableName = "[TCUpdateCountWithTriggersTable1]"; - private final String table2Name = "[TCUpdateCountWithTriggersTable2]"; - private final String sprocName = "[TCUpdateCountWithTriggersProc]"; - private final String triggerName = "[TCUpdateCountWithTriggersTrigger]"; + private final String tableName = RandomUtil.getIdentifier("TCUpdateCountWithTriggersTable1"); + private final String table2Name = RandomUtil.getIdentifier("TCUpdateCountWithTriggersTable2"); + private final String sprocName = RandomUtil.getIdentifier("TCUpdateCountWithTriggersProc"); + private final String triggerName = RandomUtil.getIdentifier("TCUpdateCountWithTriggersTrigger"); @BeforeEach public void setup() throws Exception { @@ -2085,27 +2119,36 @@ public void setup() throws Exception { try (Statement stmt = con.createStatement()) { try { - stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName - + "') drop trigger " + triggerName); + stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + + TestUtils.escapeSingleQuotes((triggerName)) + "') drop trigger " + + AbstractSQLGenerator.escapeIdentifier(triggerName)); } catch (SQLException e) { throw new SQLException(e); } - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT PRIMARY KEY)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 INT PRIMARY KEY)"); for (int i = 0; i < NUM_ROWS; i++) - stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1) VALUES (" + i + ")"); - stmt.executeUpdate( - "CREATE TABLE " + table2Name + " (NAME VARCHAR(100), col2 int identity(1,1) primary key)"); - stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('BLAH')"); - stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('FNORD')"); - stmt.executeUpdate("INSERT INTO " + table2Name + " (NAME) VALUES ('EEEP')"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (NAME VARCHAR(100), col2 int identity(1,1) primary key)"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (NAME) VALUES ('BLAH')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (NAME) VALUES ('FNORD')"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(table2Name) + + " (NAME) VALUES ('EEEP')"); - stmt.executeUpdate("Create Procedure " + sprocName + " AS " + "Begin " + " Update " + table2Name - + " SET " + " NAME = 'Update' Where NAME = 'TEST' " + "Return 0 " + "End"); + stmt.executeUpdate("Create Procedure " + AbstractSQLGenerator.escapeIdentifier(sprocName) + " AS " + + "Begin " + " Update " + AbstractSQLGenerator.escapeIdentifier(table2Name) + " SET " + + " NAME = 'Update' Where NAME = 'TEST' " + "Return 0 " + "End"); - stmt.executeUpdate("CREATE Trigger " + triggerName + " ON " + tableName + " FOR DELETE AS " - + "Begin " + "Declare @l_retstat Integer " + "Execute @l_retstat = " + sprocName + " " - + "If (@l_retstat <> 0) " + "Begin " + " Rollback Transaction " + "End " + "End"); + stmt.executeUpdate("CREATE Trigger " + AbstractSQLGenerator.escapeIdentifier(triggerName) + " ON " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " FOR DELETE AS " + "Begin " + + "Declare @l_retstat Integer " + "Execute @l_retstat = " + + AbstractSQLGenerator.escapeIdentifier(sprocName) + " " + "If (@l_retstat <> 0) " + + "Begin " + " Rollback Transaction " + "End " + "End"); } con.commit(); @@ -2121,7 +2164,8 @@ public void setup() throws Exception { public void testLastUpdateCountTrue() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); - PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?")) { + PreparedStatement ps = con.prepareStatement( + "DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 = ?")) { ps.setInt(1, 1); int updateCount = ps.executeUpdate(); @@ -2140,7 +2184,8 @@ public void testLastUpdateCountTrue() throws Exception { public void testLastUpdateCountFalse() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=false"); - PreparedStatement ps = con.prepareStatement("DELETE FROM " + tableName + " WHERE col1 = ?")) { + PreparedStatement ps = con.prepareStatement( + "DELETE FROM " + AbstractSQLGenerator.escapeIdentifier(tableName) + " WHERE col1 = ?")) { ps.setInt(1, 1); int updateCount = ps.executeUpdate(); @@ -2159,9 +2204,10 @@ public void testLastUpdateCountFalse() throws Exception { public void testPreparedStatementInsertExecInsert() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); - PreparedStatement ps = con - .prepareStatement("INSERT INTO " + tableName + " (col1) VALUES (" + (NUM_ROWS + 1) + "); " - + "EXEC " + sprocName + "; " + "UPDATE " + table2Name + " SET NAME = 'FISH'")) { + PreparedStatement ps = con.prepareStatement("INSERT INTO " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " (col1) VALUES (" + (NUM_ROWS + 1) + + "); " + "EXEC " + AbstractSQLGenerator.escapeIdentifier(sprocName) + "; " + "UPDATE " + + AbstractSQLGenerator.escapeIdentifier(table2Name) + " SET NAME = 'FISH'")) { int updateCount = ps.executeUpdate(); @@ -2181,11 +2227,13 @@ public void testStatementInsertExecInsert() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount=true"); Statement stmt = con.createStatement()) { - int updateCount = stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + (NUM_ROWS + 1) - + "); " + "EXEC " + sprocName + "; " + "UPDATE " + table2Name + " SET NAME = 'FISH'"); + int updateCount = stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1) VALUES (" + (NUM_ROWS + 1) + "); " + "EXEC " + + AbstractSQLGenerator.escapeIdentifier(sprocName) + "; " + "UPDATE " + + AbstractSQLGenerator.escapeIdentifier(table2Name) + " SET NAME = 'FISH'"); // updateCount should be from the INSERT, - // which should have affected 1 (new) row in tableName. + // which should have affected 1 (new) row in AbstractSQLGenerator.escapeIdentifier(tableName). assertEquals(updateCount, 1, "Wrong update count"); } } @@ -2195,9 +2243,9 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - TestUtils.dropTableIfExists(tableName, stmt); - TestUtils.dropTableIfExists(table2Name, stmt); - TestUtils.dropProcedureIfExists(sprocName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(table2Name), stmt); + TestUtils.dropProcedureIfExists(AbstractSQLGenerator.escapeIdentifier(sprocName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -2207,8 +2255,7 @@ public void terminate() throws Exception { @Nested public class TCUpdateCountAfterRaiseError { - String tableNameTemp = RandomUtil.getIdentifier("TCUpdateCountAfterRaiseError"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); + private final String tableName = RandomUtil.getIdentifier("TCUpdateCountAfterRaiseError"); private final String triggerName = "TCUpdateCountAfterRaiseErrorTrigger"; private final int NUM_ROWS = 3; private final String errorMessage50001InSqlAzure = "Error 50001, severity 17, state 1 was raised, but no message with that error number was found in sys.messages. If error is larger than 50000, make sure the user-defined message is added using sp_addmessage."; @@ -2220,14 +2267,17 @@ public void setup() throws Exception { try (Statement stmt = con.createStatement()) { try { - stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName - + "') drop trigger " + triggerName); + stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + + AbstractSQLGenerator.escapeIdentifier(triggerName) + "') drop trigger " + + AbstractSQLGenerator.escapeIdentifier(triggerName)); } catch (SQLException e) { System.out.println(e.toString()); } - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT primary key)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 INT primary key)"); for (int i = 0; i < NUM_ROWS; i++) - stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1) VALUES (" + i + ")"); // Skip adding message for 50001 if the target server is SQL Azure, because SQL Azure does not // support @@ -2244,9 +2294,10 @@ public void setup() throws Exception { } } - stmt.executeUpdate( - "CREATE TRIGGER " + triggerName + " ON " + tableName + " FOR INSERT AS BEGIN DELETE FROM " - + tableName + " WHERE col1 = 1 RAISERROR(50001, 17, 1) END"); + stmt.executeUpdate("CREATE TRIGGER " + AbstractSQLGenerator.escapeIdentifier(triggerName) + " ON " + + AbstractSQLGenerator.escapeIdentifier(tableName) + " FOR INSERT AS BEGIN DELETE FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName) + + " WHERE col1 = 1 RAISERROR(50001, 17, 1) END"); } con.commit(); } @@ -2261,8 +2312,10 @@ public void setup() throws Exception { public void testUpdateCountAfterRaiseError() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); - PreparedStatement pstmt = con.prepareStatement("UPDATE " + tableName - + " SET col1 = 5 WHERE col1 = 2 RAISERROR(50001, 17, 1) SELECT * FROM " + tableName)) { + PreparedStatement pstmt = con + .prepareStatement("UPDATE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " SET col1 = 5 WHERE col1 = 2 RAISERROR(50001, 17, 1) SELECT * FROM " + + AbstractSQLGenerator.escapeIdentifier(tableName))) { // enable isCloseOnCompletion try { @@ -2315,7 +2368,8 @@ public void testUpdateCountAfterRaiseError() throws Exception { public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = false"); - PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)")) { + PreparedStatement pstmt = con.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (5)")) { int updateCount = pstmt.executeUpdate(); assertEquals(updateCount, 1, "First result: should have been 1 row deleted"); @@ -2343,7 +2397,8 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exce result = pstmt.getMoreResults(); assertEquals(result, false, "Third result: wrong result type; update count expected"); assertEquals(pstmt.getUpdateCount(), 1, "Third result: wrong number of rows inserted"); - try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { int rowCount = 0; while (rs.next()) ++rowCount; @@ -2362,7 +2417,8 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountFalse() throws Exce public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); - PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tableName + " VALUES (5)")) { + PreparedStatement pstmt = con.prepareStatement( + "INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + " VALUES (5)")) { try { pstmt.executeUpdate(); @@ -2391,7 +2447,8 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Excep assertEquals(pstmt.getUpdateCount(), 1, "Second result: wrong number of rows inserted"); } - try (ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tableName)) { + try (ResultSet rs = con.createStatement() + .executeQuery("SELECT * FROM " + AbstractSQLGenerator.escapeIdentifier(tableName))) { int rowCount = 0; while (rs.next()) ++rowCount; @@ -2405,7 +2462,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { fail(e.toString()); } @@ -2415,8 +2472,7 @@ public void terminate() throws Exception { @Nested public class TCNocount { - final String tableNameTemp = RandomUtil.getIdentifier("TCNoCount"); - private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); + private final String tableName = RandomUtil.getIdentifier("TCNoCount"); private static final int NUM_ROWS = 3; @@ -2432,9 +2488,11 @@ public void setup() throws Exception { } catch (Exception e) { throw new SQLException(TestResource.getResource("R_unexpectedException"), e); } - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT primary key)"); + stmt.executeUpdate("CREATE TABLE " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1 INT primary key)"); for (int i = 0; i < NUM_ROWS; i++) - stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); + stmt.executeUpdate("INSERT INTO " + AbstractSQLGenerator.escapeIdentifier(tableName) + + " (col1) VALUES (" + i + ")"); assertEquals(stmt.isClosed(), false, TestResource.getResource("R_statementShouldBeOpened")); } @@ -2453,8 +2511,9 @@ public void testNoCountWithExecute() throws Exception { try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); Statement stmt = con.createStatement();) { - boolean isResultSet = stmt.execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" - + (NUM_ROWS + 1) + ")\n" + "select 1"); + boolean isResultSet = stmt + .execute("set nocount on\n" + "insert into " + AbstractSQLGenerator.escapeIdentifier(tableName) + + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); assertEquals(true, isResultSet, "execute() said first result was an update count"); @@ -2475,7 +2534,7 @@ public void terminate() throws Exception { try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { try { - TestUtils.dropTableIfExists(tableName, stmt); + TestUtils.dropTableIfExists(AbstractSQLGenerator.escapeIdentifier(tableName), stmt); } catch (SQLException e) { fail(e.toString()); } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java b/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java index 3f51817d8e..b0b098850c 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/AbstractTest.java @@ -79,7 +79,6 @@ public static void setup() throws Exception { info.setProperty("keyStoreLocation", jksPaths[0]); info.setProperty("keyStoreSecret", secretstrJks); } - logger.info("In AbstractTest:setup"); try { Assertions.assertNotNull(connectionString, "Connection String should not be null");